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