22
22
23
23
*/
24
24
25
+ #include < stdio.h>
25
26
#include < stdlib.h>
26
27
#include < string.h>
27
28
#include < stdbool.h>
@@ -40,75 +41,9 @@ char* ultoa(unsigned long value, char* result, int base) {
40
41
}
41
42
42
43
char * dtostrf (double number, signed char width, unsigned char prec, char *s) {
43
- bool negative = false ;
44
-
45
- if (isnan (number)) {
46
- strcpy (s, " nan" );
47
- return s;
48
- }
49
- if (isinf (number)) {
50
- strcpy (s, " inf" );
51
- return s;
52
- }
53
-
54
- char * out = s;
55
-
56
- int fillme = width; // how many cells to fill for the integer part
57
- if (prec > 0 ) {
58
- fillme -= (prec+1 );
59
- }
60
-
61
- // Handle negative numbers
62
- if (number < 0.0 ) {
63
- negative = true ;
64
- fillme--;
65
- number = -number;
66
- }
67
-
68
- // Round correctly so that print(1.999, 2) prints as "2.00"
69
- // I optimized out most of the divisions
70
- double rounding = 2.0 ;
71
- for (uint8_t i = 0 ; i < prec; ++i)
72
- rounding *= 10.0 ;
73
- rounding = 1.0 / rounding;
74
-
75
- number += rounding;
76
-
77
- // Figure out how big our number really is
78
- double tenpow = 1.0 ;
79
- int digitcount = 1 ;
80
- while (number >= 10.0 * tenpow) {
81
- tenpow *= 10.0 ;
82
- digitcount++;
83
- }
84
-
85
- number /= tenpow;
86
- fillme -= digitcount;
87
-
88
- // Pad unused cells with spaces
89
- while (fillme-- > 0 ) {
90
- *out++ = ' ' ;
91
- }
92
-
93
- // Handle negative sign
94
- if (negative) *out++ = ' -' ;
95
-
96
- // Print the digits, and if necessary, the decimal point
97
- digitcount += prec;
98
- int8_t digit = 0 ;
99
- while (digitcount-- > 0 ) {
100
- digit = (int8_t )number;
101
- if (digit > 9 ) digit = 9 ; // insurance
102
- *out++ = (char )(' 0' | digit);
103
- if ((digitcount == prec) && (prec > 0 )) {
104
- *out++ = ' .' ;
105
- }
106
- number -= digit;
107
- number *= 10.0 ;
108
- }
109
-
110
- // make sure the string is terminated
111
- *out = 0 ;
44
+ char fmt[32 ];
45
+ sprintf (fmt, " %%%d.%df" , width, prec);
46
+ sprintf (s, fmt, number);
112
47
return s;
113
48
}
114
49
0 commit comments