Skip to content

Commit 30e08c6

Browse files
committed
fix dtostrf() issue using trackerj/odometer fixes along with my own fix for string null character ending
1 parent 042d105 commit 30e08c6

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_noniso.c

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -162,46 +162,45 @@ char * dtostrf(double number, signed char width, unsigned char prec, char *s) {
162162
strcpy(s, "ovf");
163163
return s;
164164
}
165-
166165
char* out = s;
167-
int signInt_Part = 1;
168-
169166
// Handle negative numbers
170167
if (number < 0.0) {
171-
signInt_Part = -1;
168+
*out = '-';
169+
++out;
172170
number = -number;
173171
}
174172

175-
// calc left over digits
176-
if (prec > 0)
177-
{
178-
width -= (prec + 1);
179-
}
180-
181173
// Round correctly so that print(1.999, 2) prints as "2.00"
182-
double rounding = 0.5;
174+
// I optimized out most of the divisions
175+
double rounding = 2.0;
183176
for (uint8_t i = 0; i < prec; ++i)
184-
rounding /= 10.0;
177+
rounding *= 10.0;
178+
rounding = 1.0 / rounding;
185179

186180
number += rounding;
187181

188182
// Extract the integer part of the number and print it
189183
unsigned long int_part = (unsigned long)number;
190184
double remainder = number - (double)int_part;
191-
out += sprintf(out, "%*ld", width, int_part * signInt_Part);
185+
out += sprintf(out, "%d", int_part);
192186

193187
// Print the decimal point, but only if there are digits beyond
194188
if (prec > 0) {
195189
*out = '.';
196190
++out;
197-
198-
199-
for (unsigned char decShift = prec; decShift > 0; decShift--) {
200-
remainder *= 10.0;
201-
}
202-
sprintf(out, "%0*d", prec, (int)remainder);
203191
}
204192

193+
// Print the digits after the decimal point
194+
int8_t digit = 0;
195+
while (prec-- > 0) {
196+
remainder *= 10.0;
197+
digit = (int8_t)remainder;
198+
if (digit > 9) digit = 9; // insurance
199+
*out = (char)('0' | digit);
200+
++out;
201+
remainder -= digit;
202+
}
203+
*out = 0;
205204
return s;
206205
}
207206

0 commit comments

Comments
 (0)