00001
00002
00003
00004
00005
00006
00007 #include <stdlib.h>
00008 #include <stdio.h>
00009 #include <ctype.h>
00010 #include <math.h>
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #define EPSILON ((1.0/256.0)/2.0)
00021 #define GET_DEC(x) ( (x) - (float)(int)(x) )
00022
00023 char*
00024 price_to_str( float price,
00025 int *numorator,
00026 int *demoninator,
00027 int *decimal,
00028 char *fltfmt )
00029 {
00030 static char rtn[64];
00031 int whole = (int)price;
00032 float dec = GET_DEC( price ),
00033 numr;
00034
00035
00036
00037 if( fltfmt )
00038 {
00039 sprintf( rtn, fltfmt, price );
00040 *numorator = *demoninator = *decimal = 0;
00041 return rtn;
00042 }
00043
00044 numr = dec * 256;
00045
00046 {
00047 float rdec = GET_DEC( numr );
00048
00049 if( rdec < EPSILON )
00050 ;
00051 else if( (1-rdec) < EPSILON )
00052 ++numr;
00053 else
00054 {
00055 sprintf( rtn, "%f", price );
00056 *numorator = *demoninator = *decimal = 0;
00057 return rtn;
00058 }
00059 }
00060
00061
00062
00063 if( numr != 0 )
00064 {
00065 int cnt = 8;
00066
00067 while( (float)(numr)/2.0 == (float)(int)(numr/2) )
00068 {
00069 numr /= 2;
00070 --cnt;
00071 }
00072
00073
00074 if( whole<0 && numr<0.0 )
00075 numr = -numr;
00076 *numorator = (int)numr;
00077 *demoninator = (int)pow(2.0, (float)cnt);
00078 *decimal = whole;
00079 sprintf( rtn, "%d %d/%d", whole,
00080 (int)numr,
00081 *demoninator );
00082 }
00083 else
00084 {
00085 *numorator = *demoninator = 0;
00086 *decimal = whole;
00087 sprintf( rtn, "%d", whole );
00088 }
00089
00090 return rtn;
00091 }
00092