[gforth] / gforth / Attic / ecvt.c  

gforth: gforth/Attic/ecvt.c


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

CVS Admin

Powered by ViewCVS 1.0-dev
(Powered by ViewCVS)

ViewCVS and CVS Help