From d34057d03a0444717fa501d2cf11380781371b2c Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Wed, 16 Jun 2021 17:49:04 +1000 Subject: [PATCH] Round half away from zero when formatting Fixed/GuardedFixed --- src/numbers/fixed.rs | 15 ++++++++++++--- src/numbers/gfixed.rs | 15 ++++++++++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/numbers/fixed.rs b/src/numbers/fixed.rs index 8f5b6e2..01bf8c9 100644 --- a/src/numbers/fixed.rs +++ b/src/numbers/fixed.rs @@ -117,10 +117,19 @@ impl fmt::Display for Fixed { None => get_dps(), }; - let factor = IBig::from(10).pow(get_dps() - dps); - let mut result = (&self.0 / factor).abs().to_string(); + let mut result; + if dps == get_dps() { + result = self.0.clone().abs().to_string(); + } else { + // Rounding required + let factor = IBig::from(10).pow(get_dps() - dps - 1); // -1 to account for rounding digit + let mut rounded = (&self.0 / factor).abs() + IBig::from(5); // Add 5 to force round-to-nearest + rounded /= IBig::from(10); // Remove rounding digit + result = rounded.to_string(); + } - let should_add_minus = (self.0 < IBig::zero()) && result != "0"; + //let should_add_minus = (self.0 < IBig::zero()) && result != "0"; + let should_add_minus = self.0 < IBig::zero(); // Add leading 0s result = format!("{0:0>1$}", result, dps + 1); diff --git a/src/numbers/gfixed.rs b/src/numbers/gfixed.rs index ed72448..22d0e54 100644 --- a/src/numbers/gfixed.rs +++ b/src/numbers/gfixed.rs @@ -149,10 +149,19 @@ impl fmt::Display for GuardedFixed { None => get_dps(), }; - let factor = IBig::from(10).pow(get_dps() * 2 - dps); - let mut result = (&self.0 / factor).abs().to_string(); + let mut result; + if dps == get_dps() * 2 { + result = self.0.clone().abs().to_string(); + } else { + // Rounding required + let factor = IBig::from(10).pow(get_dps() * 2 - dps - 1); + let mut rounded = (&self.0 / factor).abs() + IBig::from(5); // Add 5 to force round-to-nearest + rounded /= IBig::from(10); // Remove rounding digit + result = rounded.to_string(); + } - let should_add_minus = (self.0 < IBig::zero()) && result != "0"; + //let should_add_minus = (self.0 < IBig::zero()) && result != "0"; + let should_add_minus = self.0 < IBig::zero(); // Add leading 0s result = format!("{0:0>1$}", result, dps + 1);