Skip to content

Commit 2e56b81

Browse files
committed
stdlib_noniso.cpp: Handle rounding corner case for dtostrf
Rounding must be done before separating the integral and decimal portions.
1 parent f2a001f commit 2e56b81

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

cores/arduino/WString.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ String::String(float value, unsigned char decimalPlaces)
138138

139139
if(decimalPlaces) totalSize += 1 + ((int)decimalPlaces & 0x0FF);
140140

141-
char buf[totalSize+1];
141+
char buf[totalSize + 2];
142142
*this = dtostrf(value, 0, decimalPlaces, buf);
143143
}
144144

@@ -149,7 +149,7 @@ String::String(double value, unsigned char decimalPlaces)
149149

150150
if(decimalPlaces) totalSize += 1 + ((int)decimalPlaces & 0x0FF);
151151

152-
char buf[totalSize+1];
152+
char buf[totalSize + 2];
153153
*this = dtostrf(value, 0, decimalPlaces, buf);
154154
}
155155

cores/arduino/stdlib_noniso.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,12 @@ char *dtostrf(double number, signed char width, unsigned char prec, char *s)
215215
number = -number;
216216
}
217217

218+
// rounding up to the precision
219+
rounding = 0.5;
220+
for (i = 0; i < prec; ++i)
221+
rounding /= 10.0;
222+
number += rounding;
223+
218224
// seperate integral and fractional parts
219225
integer = (unsigned long long) number;
220226
fraction = (double) (number - integer);
@@ -231,12 +237,6 @@ char *dtostrf(double number, signed char width, unsigned char prec, char *s)
231237
out += before;
232238
if (!prec) goto end;
233239

234-
// rounding up to the precision
235-
rounding = 0.5;
236-
for (i = 0; i < prec; ++i)
237-
rounding /= 10.0;
238-
fraction += rounding;
239-
240240
// generate chars for each digit of the fractional part
241241
*out++ = '.';
242242
for (i = 0; i < prec; ++i) {

0 commit comments

Comments
 (0)