Skip to content

Commit 50f30b3

Browse files
committed
stdlib_noniso.cpp: dtostrf(), subtract rounding if number is negative
If we are working with a negative number, then *adding* the rounding onto the number has the opposite to the intended effect. Need to check if the number is negative, and if so, subtract the rounding instead of adding. It may appear that a cleaner solution to this is to simply move the "handle negative numbers" block (starting on what is now line 222) before the "round up to the precision" block (starting on what is now line 202). However, I don't think this will work without a substantial re-design of this function, for the following reasons; Any leading padding must be added before handling a negative number (adding the '-' char. to output, and then flipping the number's sign for calculations). And in order to add the right amount of padding, we must run digitsBe4Decimal first, and in order to guarantee an accurate result from *that*, the rounding-up must have been done. So there's a fairly rigid order here. Oh, and I also removed the 'goto end', and the label, since an if() work just as well. Can't remember why I even added that in the first place.
1 parent 3f61b65 commit 50f30b3

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

Diff for: cores/arduino/stdlib_noniso.cpp

+14-10
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,11 @@ char *dtostrf(double number, signed char width, unsigned char prec, char *s)
203203
rounding = 0.5;
204204
for (i = 0; i < prec; ++i)
205205
rounding /= 10.0;
206-
number += rounding;
206+
207+
if (number < 0.0)
208+
number -= rounding;
209+
else
210+
number += rounding;
207211

208212
out = s;
209213
before = digitsBe4Decimal(number);
@@ -235,17 +239,17 @@ char *dtostrf(double number, signed char width, unsigned char prec, char *s)
235239

236240
out[i - 1] = ASCII_ZERO + integer;
237241
out += before;
238-
if (!prec) goto end;
239-
240-
// generate chars for each digit of the fractional part
241-
*out++ = '.';
242-
for (i = 0; i < prec; ++i) {
243-
fraction *= 10.0;
244-
digit = ((unsigned long long) fraction) % 10;
245-
*out++ = (char) (ASCII_ZERO + digit);
242+
243+
if (prec) {
244+
// generate chars for each digit of the fractional part
245+
*out++ = '.';
246+
for (i = 0; i < prec; ++i) {
247+
fraction *= 10.0;
248+
digit = ((unsigned long long) fraction) % 10;
249+
*out++ = (char) (ASCII_ZERO + digit);
250+
}
246251
}
247252

248-
end:
249253
// check if padding is required
250254
if (width > 0) {
251255
delta = width - (before + prec + 1);

0 commit comments

Comments
 (0)