about summary refs log tree commit diff
path: root/library/core/src
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2023-11-14 00:04:05 +0000
committerbors <bors@rust-lang.org>2023-11-14 00:04:05 +0000
commitb9175240ea5266ebb32ef72aa6981814d9fea014 (patch)
treefc98cef1ce6c2f3601efbb34082caff7379dd921 /library/core/src
parentba7c7a301984967c8c13adb580ef9b86ba706a83 (diff)
parent3f0908f47cff0f80bf4da69e845b6efdd333f6ea (diff)
downloadrust-b9175240ea5266ebb32ef72aa6981814d9fea014.tar.gz
rust-b9175240ea5266ebb32ef72aa6981814d9fea014.zip
Auto merge of #116301 - mj10021:issue-115737-fix, r=cuviper
fix rounding issue with exponents in fmt

fixes issue #115737 , where the decimal places are rounded incorrectly when formatting scientific notation
Diffstat (limited to 'library/core/src')
-rw-r--r--library/core/src/fmt/num.rs11
1 files changed, 8 insertions, 3 deletions
diff --git a/library/core/src/fmt/num.rs b/library/core/src/fmt/num.rs
index 4f42f73ebba..778515f8616 100644
--- a/library/core/src/fmt/num.rs
+++ b/library/core/src/fmt/num.rs
@@ -309,7 +309,6 @@ macro_rules! impl_Exp {
                     n /= 10;
                     exponent += 1;
                 }
-
                 let (added_precision, subtracted_precision) = match f.precision() {
                     Some(fmt_prec) => {
                         // number of decimal digits minus 1
@@ -331,9 +330,15 @@ macro_rules! impl_Exp {
                     let rem = n % 10;
                     n /= 10;
                     exponent += 1;
-                    // round up last digit
-                    if rem >= 5 {
+                    // round up last digit, round to even on a tie
+                    if rem > 5 || (rem == 5 && (n % 2 != 0 || subtracted_precision > 1 )) {
                         n += 1;
+                        // if the digit is rounded to the next power
+                        // instead adjust the exponent
+                        if n.ilog10() > (n - 1).ilog10() {
+                            n /= 10;
+                            exponent += 1;
+                        }
                     }
                 }
                 (n, exponent, exponent, added_precision)