Fix engineering formatting

This commit is contained in:
Austen Adler 2021-05-13 22:19:39 -04:00
parent bab2904495
commit 4e1e256461

View File

@ -404,13 +404,18 @@ fn fmt_scientific(f: f64, precision: usize) -> String {
};
let sign = if !ret.starts_with('-') { " " } else { "" };
format!("{}{}E{}{:0>pad$}", sign, ret, exp_sign, exp, pad = 2)
format!("{}{} E{}{:0>pad$}", sign, ret, exp_sign, exp, pad = 2)
}
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());
@ -471,20 +476,27 @@ mod tests {
fn test_fmt_scientific() {
for (f, p, s) in vec![
// Basic
(1.0, 0, " 1E+00"),
(-1.0, 0, "-1E+00"),
(100.0, 0, " 1E+02"),
(0.1, 0, " 1E-01"),
(0.01, 0, " 1E-02"),
(-0.1, 0, "-1E-01"),
(1.0, 0, " 1 E+00"),
(-1.0, 0, "-1 E+00"),
(100.0, 0, " 1 E+02"),
(0.1, 0, " 1 E-01"),
(0.01, 0, " 1 E-02"),
(-0.1, 0, "-1 E-01"),
// i
(1.0, 0, " 1E+00"),
(1.0, 0, " 1 E+00"),
// Precision
(-0.123456789, 3, "-1.235E-01"),
(-0.123456789, 2, "-1.23E-01"),
(-0.123456789, 2, "-1.23E-01"),
(-1e99, 2, "-1.00E+99"),
(-1e100, 2, "-1.00E+100"),
(-0.123456789, 3, "-1.235 E-01"),
(-0.123456789, 2, "-1.23 E-01"),
(-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);
}