Round half away from zero when formatting Fixed/GuardedFixed

This commit is contained in:
RunasSudo 2021-06-16 17:49:04 +10:00
parent 8829fa5a7b
commit d34057d03a
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A
2 changed files with 24 additions and 6 deletions

View File

@ -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);

View File

@ -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);