From 0a8155b5c2c3fc9d68e4547034f3a31633a8a2c3 Mon Sep 17 00:00:00 2001 From: Nicolas Boichat Date: Mon, 3 Mar 2025 15:18:00 +0100 Subject: [PATCH] uucore: format: Fix capitalization of 0 in scientific formating 0.0E+00 was not capitalized properly when using `%E` format. Fixes #7382. Test: cargo test --package uucore --all-features float Test: cargo run printf "%E\n" 0 => 0.000000E+00 --- .../src/lib/features/format/num_format.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/uucore/src/lib/features/format/num_format.rs b/src/uucore/src/lib/features/format/num_format.rs index 0acec0598..6caf1bfce 100644 --- a/src/uucore/src/lib/features/format/num_format.rs +++ b/src/uucore/src/lib/features/format/num_format.rs @@ -350,11 +350,16 @@ fn format_float_scientific( case: Case, force_decimal: ForceDecimal, ) -> String { + let exp_char = match case { + Case::Lowercase => 'e', + Case::Uppercase => 'E', + }; + if f == 0.0 { return if force_decimal == ForceDecimal::Yes && precision == 0 { - "0.e+00".into() + format!("0.{exp_char}+00") } else { - format!("{:.*}e+00", precision, 0.0) + format!("{:.*}{exp_char}+00", precision, 0.0) }; } @@ -375,11 +380,6 @@ fn format_float_scientific( "" }; - let exp_char = match case { - Case::Lowercase => 'e', - Case::Uppercase => 'E', - }; - format!("{normalized:.precision$}{additional_dot}{exp_char}{exponent:+03}") } @@ -582,6 +582,10 @@ mod test { assert_eq!(f(12.345_678_9), "1.234568e+01"); assert_eq!(f(1_000_000.0), "1.000000e+06"); assert_eq!(f(99_999_999.0), "1.000000e+08"); + + let f = |x| format_float_scientific(x, 6, Case::Uppercase, ForceDecimal::No); + assert_eq!(f(0.0), "0.000000E+00"); + assert_eq!(f(123_456.789), "1.234568E+05"); } #[test]