diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ebc3fb..2b4f00f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * Add the `ValueType` enum that represents the type of a value for easier comparisons and matchings * Add `EvalexprResult` type that uses the `EvalexprError` type (renamed from `Error`) * Add `Node::eval_number` and `Node::eval_number_with_context` to evaluate to int or float and silently converting to float + * Add `eval_number` and `eval_number_with_context` crate methods to evaluate to int or float and silently converting to float ### Removed diff --git a/src/interface/mod.rs b/src/interface/mod.rs index afd7725..e2b9b52 100644 --- a/src/interface/mod.rs +++ b/src/interface/mod.rs @@ -104,6 +104,19 @@ pub fn eval_float(string: &str) -> Result { } } +/// Evaluate the given expression string into a float. +/// If the result of the expression is an integer, it is silently converted into a float. +/// +/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* +pub fn eval_number(string: &str) -> Result { + match eval(string) { + Ok(Value::Float(float)) => Ok(float), + Ok(Value::Int(int)) => Ok(int as FloatType), + Ok(value) => Err(EvalexprError::expected_float(value)), + Err(error) => Err(error), + } +} + /// Evaluate the given expression string into a boolean. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* @@ -162,6 +175,22 @@ pub fn eval_float_with_context( } } +/// Evaluate the given expression string into a float with the given context. +/// If the result of the expression is an integer, it is silently converted into a float. +/// +/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* +pub fn eval_number_with_context( + string: &str, + context: &Context, +) -> Result { + match eval_with_context(string, context) { + Ok(Value::Float(float)) => Ok(float), + Ok(Value::Int(int)) => Ok(int as FloatType), + Ok(value) => Err(EvalexprError::expected_float(value)), + Err(error) => Err(error), + } +} + /// Evaluate the given expression string into a boolean with the given context. /// /// *See the [crate doc](index.html) for more examples and explanations of the expression format.* diff --git a/tests/integration.rs b/tests/integration.rs index 301ad14..7f9394d 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -345,6 +345,8 @@ fn test_shortcut_functions() { assert_eq!(eval_float_with_context("3.3", &context), Ok(3.3)); assert_eq!(eval_int("3"), Ok(3)); assert_eq!(eval_int_with_context("3", &context), Ok(3)); + assert_eq!(eval_number("3"), Ok(3.0)); + assert_eq!(eval_number_with_context("3", &context), Ok(3.0)); assert_eq!(eval_boolean("true"), Ok(true)); assert_eq!(eval_boolean_with_context("true", &context), Ok(true)); assert_eq!(eval_tuple("3,3"), Ok(vec![Value::Int(3), Value::Int(3)]));