diff --git a/crates/nu-command/src/math/round.rs b/crates/nu-command/src/math/round.rs index 9eb28249e1..ad4c378bec 100644 --- a/crates/nu-command/src/math/round.rs +++ b/crates/nu-command/src/math/round.rs @@ -75,11 +75,33 @@ impl Command for SubCommand { span: Span::test_data(), }), }, + Example { + description: "Apply negative precision to a list of numbers", + example: "[123, 123.3, -123.4] | math round -p -1", + result: Some(Value::List { + vals: vec![ + Value::test_int(120), + Value::test_int(120), + Value::test_int(-120), + ], + span: Span::test_data(), + }), + }, ] } } fn operate(value: Value, head: Span, precision: Option) -> Value { + // We treat int values as float values in order to avoid code repetition in the match closure + let value = if let Value::Int { val, span } = value { + Value::Float { + val: val as f64, + span, + } + } else { + value + }; + match value { Value::Float { val, span } => match precision { Some(precision_number) => Value::Float { @@ -92,7 +114,6 @@ fn operate(value: Value, head: Span, precision: Option) -> Value { span, }, }, - Value::Int { .. } => value, Value::Error { .. } => value, other => Value::Error { error: Box::new(ShellError::OnlySupportsThisInputType { diff --git a/crates/nu-command/tests/commands/math/round.rs b/crates/nu-command/tests/commands/math/round.rs index 2bec436a64..6b93ebd083 100644 --- a/crates/nu-command/tests/commands/math/round.rs +++ b/crates/nu-command/tests/commands/math/round.rs @@ -2,20 +2,35 @@ use nu_test_support::nu; #[test] fn can_round_very_large_numbers() { - let actual = nu!( - cwd: ".", - "echo 18.1372544780074142289927665486772012345 | math round" - ); + let actual = nu!("18.1372544780074142289927665486772012345 | math round"); assert_eq!(actual.out, "18") } #[test] fn can_round_very_large_numbers_with_precision() { - let actual = nu!( - cwd: ".", - "echo 18.13725447800741422899276654867720121457878988 | math round -p 10" - ); + let actual = nu!("18.13725447800741422899276654867720121457878988 | math round -p 10"); assert_eq!(actual.out, "18.137254478") } + +#[test] +fn can_round_integer_with_negative_precision() { + let actual = nu!("123 | math round -p -1"); + + assert_eq!(actual.out, "120") +} + +#[test] +fn can_round_float_with_negative_precision() { + let actual = nu!("123.3 | math round -p -1"); + + assert_eq!(actual.out, "120") +} + +#[test] +fn fails_with_wrong_input_type() { + let actual = nu!("\"not_a_number\" | math round"); + + assert!(actual.err.contains("Input type not supported")) +}