From 2eb0b6dfe09c61a84814ea5aa391bad5c752dc80 Mon Sep 17 00:00:00 2001 From: Daniel Hofstetter Date: Thu, 27 Oct 2022 15:33:20 +0200 Subject: [PATCH] numfmt: round values if precision is 0 --- src/uu/numfmt/src/format.rs | 3 +-- tests/by-util/test_numfmt.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/uu/numfmt/src/format.rs b/src/uu/numfmt/src/format.rs index 5e61ce794..b97993f21 100644 --- a/src/uu/numfmt/src/format.rs +++ b/src/uu/numfmt/src/format.rs @@ -272,14 +272,13 @@ fn transform_to( let (i2, s) = consider_suffix(s, &opts.to, round_method, precision)?; let i2 = i2 / (opts.to_unit as f64); Ok(match s { - None if precision > 0 => { + None => { format!( "{:.precision$}", round_with_precision(i2, round_method, precision), precision = precision ) } - None => format!("{}", i2), Some(s) if precision > 0 => { format!( "{:.precision$}{}", diff --git a/tests/by-util/test_numfmt.rs b/tests/by-util/test_numfmt.rs index 72a9e39a9..821b8e70b 100644 --- a/tests/by-util/test_numfmt.rs +++ b/tests/by-util/test_numfmt.rs @@ -530,7 +530,7 @@ fn test_round() { new_ucmd!() .args(&[ "--to=si", - &format!("--round={}", method), + &format!("--round={method}"), "--", "9001", "-9001", @@ -542,6 +542,32 @@ fn test_round() { } } +#[test] +fn test_round_with_to_unit() { + for (method, exp) in [ + ("from-zero", ["6", "-6", "5.9", "-5.9", "5.86", "-5.86"]), + ("towards-zero", ["5", "-5", "5.8", "-5.8", "5.85", "-5.85"]), + ("up", ["6", "-5", "5.9", "-5.8", "5.86", "-5.85"]), + ("down", ["5", "-6", "5.8", "-5.9", "5.85", "-5.86"]), + ("nearest", ["6", "-6", "5.9", "-5.9", "5.86", "-5.86"]), + ] { + new_ucmd!() + .args(&[ + "--to-unit=1024", + &format!("--round={method}"), + "--", + "6000", + "-6000", + "6000.0", + "-6000.0", + "6000.00", + "-6000.00", + ]) + .succeeds() + .stdout_only(exp.join("\n") + "\n"); + } +} + #[test] fn test_suffix_is_added_if_not_supplied() { new_ucmd!()