Fix engineering formatting
This commit is contained in:
parent
bab2904495
commit
4e1e256461
20
src/main.rs
20
src/main.rs
@ -410,7 +410,12 @@ fn fmt_scientific(f: f64, precision: usize) -> String {
|
||||
fn fmt_engineering(f: f64, precision: usize) -> String {
|
||||
// Format the string so the first digit is always in the first column, and remove '.'. Requested precision + 2 to account for using 1, 2, or 3 digits for the whole portion of the string
|
||||
// 1,000 => 1000E3
|
||||
let all = format!(" {:.precision$E}", f, precision = precision + 2).replacen(".", "", 1);
|
||||
let all = format!(" {:.precision$E}", f, precision = precision)
|
||||
// Remove . since it can be moved
|
||||
.replacen(".", "", 1)
|
||||
// Add 00E before E here so the length is enough for slicing below
|
||||
.replacen("E", "00E", 1);
|
||||
println!("{}", all);
|
||||
// Extract mantissa and the string representation of the exponent. Unwrap should be safe as formatter will insert E
|
||||
// 1000E3 => (1000, E3)
|
||||
let (num_str, exp_str) = all.split_at(all.find('E').unwrap());
|
||||
@ -485,6 +490,13 @@ mod tests {
|
||||
(-0.123456789, 2, "-1.23 E-01"),
|
||||
(-1e99, 2, "-1.00 E+99"),
|
||||
(-1e100, 2, "-1.00 E+100"),
|
||||
// Rounding
|
||||
(0.5, 2, " 5.00 E-01"),
|
||||
(0.5, 1, " 5.0 E-01"),
|
||||
(0.5, 0, " 5 E-01"),
|
||||
(1.5, 2, " 1.50 E+00"),
|
||||
(1.5, 1, " 1.5 E+00"),
|
||||
(1.5, 0, " 2 E+00"),
|
||||
] {
|
||||
assert_eq!(fmt_scientific(f, p), s);
|
||||
}
|
||||
@ -526,6 +538,12 @@ mod tests {
|
||||
(0.001, 2, " 1.00 E-03"),
|
||||
(0.0001, 2, " 100.00 E-06"),
|
||||
// Rounding
|
||||
(0.5, 2, " 500.00 E-03"),
|
||||
(0.5, 1, " 500.0 E-03"),
|
||||
(0.5, 0, " 500. E-03"),
|
||||
(1.5, 2, " 1.50 E+00"),
|
||||
(1.5, 1, " 1.5 E+00"),
|
||||
(1.5, 0, " 2. E+00"),
|
||||
] {
|
||||
assert_eq!(fmt_engineering(f, c), s);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user