[gforth] / gforth / Attic / ecvt.c  

gforth: gforth/Attic/ecvt.c


1 : pazsan 1.1 #include <math.h>
2 :    
3 :     #define MAXCONV 0x40
4 :     char scratch[MAXCONV];
5 :    
6 :     char* ecvt(double x, int len, int* exp, int* sign)
7 :     {
8 :     int i, j;
9 :     double z;
10 :    
11 :     if(len > (MAXCONV-1)) len = MAXCONV-1;
12 :    
13 :     if(x<0)
14 :     {
15 :     *sign = 1;
16 :     x = -x;
17 :     }
18 :     else
19 :     {
20 :     *sign = 0;
21 :     }
22 :    
23 :     if(x==0)
24 :     {
25 :     *exp=0;
26 :     return "0";
27 :     }
28 :    
29 :     *exp=(int)floor(log10(x));
30 :     x = x / pow10((double)*exp);
31 :    
32 :     *exp += 1;
33 :    
34 :     for(i=0; i < len; i++)
35 :     {
36 :     z=floor(x);
37 :     scratch[i]='0'+(char)((int)z);
38 :     x = (x-z)*10;
39 :     }
40 :    
41 :     if((x >= 5) && i)
42 :     {
43 :     for(j=i-1; j>=0; j--)
44 :     {
45 :     if(scratch[j]!='9')
46 :     {
47 :     scratch[j]+=1; break;
48 :     }
49 :     else
50 :     {
51 :     scratch[j]='0';
52 :     }
53 :     }
54 :     if(j==0)
55 :     {
56 :     scratch[0]='1';
57 :     *exp += 1;
58 :     }
59 :     }
60 :    
61 :     scratch[i]='\0';
62 :    
63 :     return scratch;
64 :     }
65 :    
66 :     #ifdef TEST
67 :     int main(int argc, char ** argv)
68 :     {
69 :     int a, b;
70 :     char * conv=ecvt(PI*1e10,20,&a,&b);
71 :    
72 :     printf("ecvt Test: %f -> %s, %d, %d\n",PI,conv,a,b);
73 :     }
74 :     #endif

CVS Admin

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help