From 639617bec3bf0d328c508b9554bf194b66c42470 Mon Sep 17 00:00:00 2001 From: Ahmed Shehab Date: Wed, 10 Jul 2024 12:20:43 +0300 Subject: [PATCH 1/2] tinystdio: Add a fix for rounding in case of 0 decimal places for fmode before this change, in case of rouding to 0 decimal places with fmode for 0 < x < 1 some numbers get printed incorrectly such as 0,45 gets rounded to 1 instead of 0 it's because rounding happens in dtoa_ryu.c d2d function then another rounding happens in vfprintf function itself, because that cascading rounding results in incorrect results incase of rounding to 0 decimal places, this change prevents the extra rounding that happens in dtoa_ryu.c and rely on vfprintf rounding for this case. Signed-off-by: Ahmed Shehab --- newlib/libc/tinystdio/dtoa_ryu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/newlib/libc/tinystdio/dtoa_ryu.c b/newlib/libc/tinystdio/dtoa_ryu.c index 2900d22bc1..486842e270 100644 --- a/newlib/libc/tinystdio/dtoa_ryu.c +++ b/newlib/libc/tinystdio/dtoa_ryu.c @@ -283,7 +283,7 @@ d2d(const uint64_t ieeeMantissa, const uint32_t ieeeExponent, int max_digits, bo // We need to take vr + 1 if vr is outside bounds or we need to round up. // I don't know if the 'truncate_max' case is entirely correct; need some tests - uint8_t carry = ((!truncate_max && vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5); + uint8_t carry = (((!truncate_max && vr == vm && (!acceptBounds || !vmIsTrailingZeros)) || lastRemovedDigit >= 5) && !(fmode && max_decimals == 0)); output += carry; int len = decimalLength17(output); From 9ddc11235be3247edbdf85950a724af6286caf3b Mon Sep 17 00:00:00 2001 From: Ahmed Shehab Date: Wed, 10 Jul 2024 12:37:46 +0300 Subject: [PATCH 2/2] Added a testcase to test printf function rounding with 0 precision Signed-off-by: Ahmed Shehab --- test/testcases.c | 1 + 1 file changed, 1 insertion(+) diff --git a/test/testcases.c b/test/testcases.c index aa5f0a2b67..84ef3ff027 100644 --- a/test/testcases.c +++ b/test/testcases.c @@ -296,6 +296,7 @@ result |= test(__LINE__, "8.6000", "%2.4f", 8.6); result |= test(__LINE__, "0.600000", "%0f", 0.6); result |= test(__LINE__, "1", "%.0f", 0.6); + result |= test(__LINE__, "0", "%.0f", 0.45); result |= test(__LINE__, "8.6000e+00", "%2.4e", 8.6); result |= test(__LINE__, " 8.6000e+00", "% 2.4e", 8.6); result |= test(__LINE__, "-8.6000e+00", "% 2.4e", -8.6);