Skip to content

Commit cf2aa74

Browse files
committed
Fix trailing zeros in general formatting of floating numbers
1 parent 245ed70 commit cf2aa74

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

common/src/float_ops.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ pub fn format_exponent(precision: usize, magnitude: f64, case: Case) -> String {
140140
pub fn format_general(precision: usize, magnitude: f64, case: Case) -> String {
141141
match magnitude {
142142
magnitude if magnitude.is_finite() => {
143-
let r_exp = format!("{:.*e}", precision, magnitude);
143+
let r_exp = format!("{:.*e}", precision - 1, magnitude);
144144
let mut parts = r_exp.splitn(2, 'e');
145145
let base = parts.next().unwrap();
146146
let exponent = parts.next().unwrap().parse::<i64>().unwrap();
@@ -149,9 +149,16 @@ pub fn format_general(precision: usize, magnitude: f64, case: Case) -> String {
149149
Case::Lower => 'e',
150150
Case::Upper => 'E',
151151
};
152+
153+
let mut base = format!("{:.*}", precision + 1, base);
154+
while base.ends_with('0') || base.ends_with('.') {
155+
base.truncate(base.len() - 1);
156+
}
152157
format!("{}{}{:+#03}", base, e, exponent)
153158
} else {
154-
format!("{}", magnitude)
159+
let precision = (precision as i64) - 1 - exponent;
160+
let precision = precision as usize;
161+
format!("{:.*}", precision, magnitude)
155162
}
156163
}
157164
magnitude if magnitude.is_nan() => format_nan(case),

0 commit comments

Comments
 (0)