diff --git a/src/uucore/src/lib/features/format/num_format.rs b/src/uucore/src/lib/features/format/num_format.rs index 0acec0598a1..fac733a2253 100644 --- a/src/uucore/src/lib/features/format/num_format.rs +++ b/src/uucore/src/lib/features/format/num_format.rs @@ -293,13 +293,7 @@ impl Formatter for Float { let precision = match precision { Some(CanAsterisk::Fixed(x)) => x, - None => { - if matches!(variant, FloatVariant::Shortest) { - 6 - } else { - 0 - } - } + None => 6, // Default float precision (C standard) Some(CanAsterisk::Asterisk) => return Err(FormatError::WrongSpecType), }; @@ -350,11 +344,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 +374,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 +576,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] diff --git a/tests/by-util/test_seq.rs b/tests/by-util/test_seq.rs index 0c708506f7e..1fae070f41e 100644 --- a/tests/by-util/test_seq.rs +++ b/tests/by-util/test_seq.rs @@ -709,7 +709,30 @@ fn test_format_option() { } #[test] -#[ignore = "Need issue #2660 to be fixed"] +fn test_format_option_default_precision() { + new_ucmd!() + .args(&["-f", "%f", "0", "0.7", "2"]) + .succeeds() + .stdout_only("0.000000\n0.700000\n1.400000\n"); +} + +#[test] +fn test_format_option_default_precision_short() { + new_ucmd!() + .args(&["-f", "%g", "0", "0.987654321", "2"]) + .succeeds() + .stdout_only("0\n0.987654\n1.97531\n"); +} + +#[test] +fn test_format_option_default_precision_scientific() { + new_ucmd!() + .args(&["-f", "%E", "0", "0.7", "2"]) + .succeeds() + .stdout_only("0.000000E+00\n7.000000E-01\n1.400000E+00\n"); +} + +#[test] fn test_auto_precision() { new_ucmd!() .args(&["1", "0x1p-1", "2"]) @@ -718,7 +741,6 @@ fn test_auto_precision() { } #[test] -#[ignore = "Need issue #3318 to be fixed"] fn test_undefined() { new_ucmd!() .args(&["1e-9223372036854775808"])