math::abs of int returns int

This commit is contained in:
LinuxHeki 2023-05-21 09:12:12 +02:00
parent 9bbb152b4a
commit d9698df268
2 changed files with 12 additions and 5 deletions

View File

@ -78,9 +78,6 @@ pub fn builtin_function(identifier: &str) -> Option<Function> {
"math::cbrt" => simple_math!(cbrt), "math::cbrt" => simple_math!(cbrt),
// Hypotenuse // Hypotenuse
"math::hypot" => simple_math!(hypot, 2), "math::hypot" => simple_math!(hypot, 2),
// Absolute
"math::abs" => simple_math!(abs),
// Rounding
"floor" => simple_math!(floor), "floor" => simple_math!(floor),
"round" => simple_math!(round), "round" => simple_math!(round),
"ceil" => simple_math!(ceil), "ceil" => simple_math!(ceil),
@ -89,6 +86,14 @@ pub fn builtin_function(identifier: &str) -> Option<Function> {
"math::is_finite" => float_is(FloatType::is_finite), "math::is_finite" => float_is(FloatType::is_finite),
"math::is_infinite" => float_is(FloatType::is_infinite), "math::is_infinite" => float_is(FloatType::is_infinite),
"math::is_normal" => float_is(FloatType::is_normal), "math::is_normal" => float_is(FloatType::is_normal),
// Absolute
"math::abs" => Some(Function::new(|argument| {
match argument {
Value::Float(num) => Ok(Value::Float(num.abs())),
Value::Int(num) => Ok(Value::Int(num.abs())),
_ => Err(EvalexprError::ExpectedNumber { actual: argument.clone() }),
}
})),
// Other // Other
"typeof" => Some(Function::new(move |argument| { "typeof" => Some(Function::new(move |argument| {
Ok(match argument { Ok(match argument {

View File

@ -364,8 +364,10 @@ fn test_builtin_functions() {
Ok(Value::Float((8.2 as FloatType).hypot(1.1))) Ok(Value::Float((8.2 as FloatType).hypot(1.1)))
); );
// Absolute // Absolute
assert_eq!(eval("math::abs(15)"), Ok(Value::Float(15.0))); assert_eq!(eval("math::abs(15.4)"), Ok(Value::Float(15.4)));
assert_eq!(eval("math::abs(-15)"), Ok(Value::Float(15.0))); assert_eq!(eval("math::abs(-15.4)"), Ok(Value::Float(15.4)));
assert_eq!(eval("math::abs(15)"), Ok(Value::Int(15)));
assert_eq!(eval("math::abs(-15)"), Ok(Value::Int(15)));
// Rounding // Rounding
assert_eq!(eval("floor(1.1)"), Ok(Value::Float(1.0))); assert_eq!(eval("floor(1.1)"), Ok(Value::Float(1.0)));
assert_eq!(eval("floor(1.9)"), Ok(Value::Float(1.0))); assert_eq!(eval("floor(1.9)"), Ok(Value::Float(1.0)));