1: /* cheap ecvt replacement
2:
3: Copyright (C) 1998,2000,2007 Free Software Foundation, Inc.
4:
5: This file is part of Gforth.
6:
7: Gforth is free software; you can redistribute it and/or
8: modify it under the terms of the GNU General Public License
9: as published by the Free Software Foundation, either version 3
10: of the License, or (at your option) any later version.
11:
12: This program is distributed in the hope that it will be useful,
13: but WITHOUT ANY WARRANTY; without even the implied warranty of
14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: GNU General Public License for more details.
16:
17: You should have received a copy of the GNU General Public License
18: along with this program; if not, see http://www.gnu.org/licenses/.
19: */
20:
21: #include <stdio.h>
22: #include "config.h"
23: #include <math.h>
24: extern double floor(double);
25: extern double pow10(double);
26:
27: #define MAXCONV 0x40
28: char scratch[MAXCONV];
29:
30: char* ecvt(double x, int len, int* exp, int* sign)
31: {
32: int i, j;
33: double z;
34:
35: if (isnan(x)) {
36: *sign=0;
37: *exp=0;
38: return "nan";
39: }
40: if (isinf(x)) {
41: *sign=0; /* this mimics the glibc ecvt */
42: *exp=0;
43: if (x<0)
44: return "-inf";
45: else
46: return "inf";
47: }
48:
49: if(len > (MAXCONV-1)) len = MAXCONV-1;
50:
51: if(x<0)
52: {
53: *sign = 1;
54: x = -x;
55: }
56: else
57: {
58: *sign = 0;
59: }
60:
61: if(x==0)
62: *exp=-1;
63: else
64: *exp=(int)floor(log10(x));
65: x = x / pow10((double)*exp);
66:
67: *exp += 1;
68:
69: for(i=0; i < len; i++)
70: {
71: z=floor(x);
72: if(z<0) z = 0;
73: scratch[i]='0'+(char)((int)z);
74: x = (x-z)*10;
75: }
76:
77: if((x >= 5) && i)
78: {
79: for(j=i-1; j>=0; j--)
80: {
81: if(scratch[j]!='9')
82: {
83: scratch[j]+=1; break;
84: }
85: else
86: {
87: scratch[j]='0';
88: }
89: }
90: if(j<0)
91: {
92: scratch[0]='1';
93: *exp += 1;
94: }
95: }
96:
97: scratch[i]='\0';
98:
99: return scratch;
100: }
101:
102: #ifdef TEST
103: int main(int argc, char ** argv)
104: {
105: int a, b;
106: char * conv=ecvt(9e0,20,&a,&b);
107:
108: printf("ecvt Test: %f -> %s, %d, %d\n",9e0,conv,a,b);
109: }
110: #endif
111:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>