From 9c0bf0ec08765ca5596504b8a021edfcfec27715 Mon Sep 17 00:00:00 2001 From: pocopepe Date: Thu, 23 Apr 2026 16:32:13 +0530 Subject: [PATCH] numfmt: cap IEC precision at 3 decimals --- src/uu/numfmt/src/format.rs | 8 +++++++- tests/by-util/test_numfmt.rs | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/uu/numfmt/src/format.rs b/src/uu/numfmt/src/format.rs index 8e23684f4ed..b4bf4cd23df 100644 --- a/src/uu/numfmt/src/format.rs +++ b/src/uu/numfmt/src/format.rs @@ -519,8 +519,14 @@ fn consider_suffix( _ => return Err(translate!("numfmt-error-number-too-big")), }; + // iec caps at 3 decimals to match gnu, si stays as is + let effective_precision = if matches!(u, Unit::Iec(_)) { + precision.min(3) + } else { + precision + }; let v = if precision > 0 { - round_with_precision(n / bases[i], round_method, precision) + round_with_precision(n / bases[i], round_method, effective_precision) } else { div_round(n, bases[i], round_method) }; diff --git a/tests/by-util/test_numfmt.rs b/tests/by-util/test_numfmt.rs index 54c3fe77905..b73dc1c4875 100644 --- a/tests/by-util/test_numfmt.rs +++ b/tests/by-util/test_numfmt.rs @@ -1524,3 +1524,28 @@ fn test_ignores_invalid_mode_issue11935() { .stderr_is("numfmt: invalid suffix in input: '1e5'\n") .stdout_is("100\n1e5\n200\n"); } + +#[test] +fn test_iec_format_precision_cap() { + // gnu zero pads after 3 decimals on iec + let cases = [ + ("1500", "1.46500K"), + ("999999", "976.56200K"), + ("310174", "302.90500K"), + ]; + for (input, expected) in cases { + new_ucmd!() + .args(&["--to=iec", "--format=%.5f", input]) + .succeeds() + .stdout_is(format!("{expected}\n")); + } +} + +#[test] +fn test_si_format_precision_no_cap() { + // si shouldn't get the cap, full precision + new_ucmd!() + .args(&["--to=si", "--format=%.5f", "1234567"]) + .succeeds() + .stdout_is("1.23457M\n"); +}