Skip to content

Commit e348e13

Browse files
pocopepecakebaker
authored andcommitted
numfmt: cap IEC precision at 3 decimals
1 parent e50f0d0 commit e348e13

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/uu/numfmt/src/format.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,8 +519,14 @@ fn consider_suffix(
519519
_ => return Err(translate!("numfmt-error-number-too-big")),
520520
};
521521

522+
// iec caps at 3 decimals to match gnu, si stays as is
523+
let effective_precision = if matches!(u, Unit::Iec(_)) {
524+
precision.min(3)
525+
} else {
526+
precision
527+
};
522528
let v = if precision > 0 {
523-
round_with_precision(n / bases[i], round_method, precision)
529+
round_with_precision(n / bases[i], round_method, effective_precision)
524530
} else {
525531
div_round(n, bases[i], round_method)
526532
};

tests/by-util/test_numfmt.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,3 +1524,28 @@ fn test_ignores_invalid_mode_issue11935() {
15241524
.stderr_is("numfmt: invalid suffix in input: '1e5'\n")
15251525
.stdout_is("100\n1e5\n200\n");
15261526
}
1527+
1528+
#[test]
1529+
fn test_iec_format_precision_cap() {
1530+
// gnu zero pads after 3 decimals on iec
1531+
let cases = [
1532+
("1500", "1.46500K"),
1533+
("999999", "976.56200K"),
1534+
("310174", "302.90500K"),
1535+
];
1536+
for (input, expected) in cases {
1537+
new_ucmd!()
1538+
.args(&["--to=iec", "--format=%.5f", input])
1539+
.succeeds()
1540+
.stdout_is(format!("{expected}\n"));
1541+
}
1542+
}
1543+
1544+
#[test]
1545+
fn test_si_format_precision_no_cap() {
1546+
// si shouldn't get the cap, full precision
1547+
new_ucmd!()
1548+
.args(&["--to=si", "--format=%.5f", "1234567"])
1549+
.succeeds()
1550+
.stdout_is("1.23457M\n");
1551+
}

0 commit comments

Comments
 (0)