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