From 34b4853890d9fe48c9c51cff3e4218658220f6f6 Mon Sep 17 00:00:00 2001 From: Daniel Hofstetter Date: Sun, 24 Jul 2022 14:06:42 +0200 Subject: [PATCH] numfmt: don't round floats if --from is "none" --- src/uu/numfmt/src/format.rs | 11 ++++++++++- src/uu/numfmt/src/units.rs | 1 + tests/by-util/test_numfmt.rs | 8 ++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/uu/numfmt/src/format.rs b/src/uu/numfmt/src/format.rs index 0512779ca..aa55104a3 100644 --- a/src/uu/numfmt/src/format.rs +++ b/src/uu/numfmt/src/format.rs @@ -145,7 +145,16 @@ fn transform_from(s: &str, opts: &TransformOptions) -> Result { let (i, suffix) = parse_suffix(s)?; let i = i * (opts.from_unit as f64); - remove_suffix(i, suffix, &opts.from).map(|n| if n < 0.0 { -n.abs().ceil() } else { n.ceil() }) + remove_suffix(i, suffix, &opts.from).map(|n| { + // GNU numfmt doesn't round values if no --from argument is provided by the user + if opts.from == Unit::None { + n + } else if n < 0.0 { + -n.abs().ceil() + } else { + n.ceil() + } + }) } /// Divide numerator by denominator, with rounding. diff --git a/src/uu/numfmt/src/units.rs b/src/uu/numfmt/src/units.rs index a2c7b3568..4a0b8a36e 100644 --- a/src/uu/numfmt/src/units.rs +++ b/src/uu/numfmt/src/units.rs @@ -17,6 +17,7 @@ pub const IEC_BASES: [f64; 10] = [ pub type WithI = bool; +#[derive(PartialEq)] pub enum Unit { Auto, Si, diff --git a/tests/by-util/test_numfmt.rs b/tests/by-util/test_numfmt.rs index f52c777b5..089a6b37a 100644 --- a/tests/by-util/test_numfmt.rs +++ b/tests/by-util/test_numfmt.rs @@ -2,6 +2,14 @@ use crate::common::util::*; +#[test] +fn test_should_not_round_floats() { + new_ucmd!() + .args(&["0.99", "1.01", "1.1", "1.22", ".1", "-0.1"]) + .succeeds() + .stdout_is("0.99\n1.01\n1.1\n1.22\n0.1\n-0.1\n"); +} + #[test] fn test_from_si() { new_ucmd!()