Round half away from zero when formatting Fixed/GuardedFixed
This commit is contained in:
parent
8829fa5a7b
commit
d34057d03a
@ -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);
|
||||
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user