From da59cf1411344dca6c630383b240365334dcd40c Mon Sep 17 00:00:00 2001 From: Michael Vogt Date: Mon, 1 Apr 2024 09:59:21 +0200 Subject: [PATCH] du: make `-h` the same precision as GNU coreutils When printing the `du -h` output GNU coreutils does not print fractions of the size, only the full number. E.g.: ``` truncate -s12M a du -h --apparent-size a 12M a ``` Align our version to do the same. Closes: #6159 --- src/uu/du/src/du.rs | 2 +- tests/by-util/test_du.rs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index b71d5f44c13..51040e5f6f3 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -555,7 +555,7 @@ impl StatPrinter { for &(unit, power) in &UNITS { let limit = multiplier.pow(power); if size >= limit { - return format!("{:.1}{}", (size as f64) / (limit as f64), unit); + return format!("{:.0}{}", (size as f64) / (limit as f64), unit); } } format!("{size}B") diff --git a/tests/by-util/test_du.rs b/tests/by-util/test_du.rs index 92469b6f52d..d1ed5281af2 100644 --- a/tests/by-util/test_du.rs +++ b/tests/by-util/test_du.rs @@ -543,6 +543,22 @@ fn test_du_h_flag_empty_file() { .stdout_only("0\tempty.txt\n"); } +#[test] +fn test_du_h_precision() { + let (at, mut ucmd) = at_and_ucmd!(); + + let fpath = at.plus("12M.txt"); + std::fs::File::create(&fpath) + .expect("cannot create test file") + .set_len(12 * 1024 * 1024) + .expect("cannot truncate test len to size"); + ucmd.arg("-h") + .arg("--apparent-size") + .arg(&fpath) + .succeeds() + .stdout_only(format!("12M\t{}\n", &fpath.to_string_lossy())); +} + #[cfg(feature = "touch")] #[test] fn test_du_time() {