Add support for scientific notation of the form <coefficient>e{+,-,}<exponent>

This commit is contained in:
Dennis Marttinen 2021-07-20 16:30:45 +03:00
parent 0e139e6d4d
commit fbbecc766f
No known key found for this signature in database
GPG Key ID: 806207C0CC2D0C6B
2 changed files with 26 additions and 1 deletions

View File

@ -354,9 +354,27 @@ fn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> EvalexprResult<Vec<T
Some(Token::Float(number)) Some(Token::Float(number))
} else if let Ok(boolean) = literal.parse::<bool>() { } else if let Ok(boolean) = literal.parse::<bool>() {
Some(Token::Boolean(boolean)) Some(Token::Boolean(boolean))
} else {
// If there are two tokens following this one, check if the next one is
// a plus or a minus. If so, then attempt to parse all three tokens as a
// scientific notation number of the form `<coefficient>e{+,-}<exponent>`,
// for example [Literal("10e"), Minus, Literal("3")] => "1e-3".parse().
match (second, third) {
(Some(s), Some(t))
if s == PartialToken::Minus || s == PartialToken::Plus =>
{
if let Ok(number) =
format!("{}{}{}", literal, s, t).parse::<FloatType>()
{
cutoff = 3;
Some(Token::Float(number))
} else { } else {
Some(Token::Identifier(literal.to_string())) Some(Token::Identifier(literal.to_string()))
} }
}
_ => Some(Token::Identifier(literal.to_string())),
}
}
}, },
PartialToken::Whitespace => { PartialToken::Whitespace => {
cutoff = 1; cutoff = 1;

View File

@ -17,6 +17,11 @@ fn test_unary_examples() {
assert_eq!(eval("-3"), Ok(Value::Int(-3))); assert_eq!(eval("-3"), Ok(Value::Int(-3)));
assert_eq!(eval("-3.6"), Ok(Value::Float(-3.6))); assert_eq!(eval("-3.6"), Ok(Value::Float(-3.6)));
assert_eq!(eval("----3"), Ok(Value::Int(3))); assert_eq!(eval("----3"), Ok(Value::Int(3)));
assert_eq!(eval("1e0"), Ok(Value::Float(1.0)));
assert_eq!(eval("1e-0"), Ok(Value::Float(1.0)));
assert_eq!(eval("10e3"), Ok(Value::Float(10000.0)));
assert_eq!(eval("10e+3"), Ok(Value::Float(10000.0)));
assert_eq!(eval("10e-3"), Ok(Value::Float(0.01)));
} }
#[test] #[test]
@ -41,6 +46,8 @@ fn test_binary_examples() {
assert_eq!(eval("3+-1"), Ok(Value::Int(2))); assert_eq!(eval("3+-1"), Ok(Value::Int(2)));
assert_eq!(eval("-3-5"), Ok(Value::Int(-8))); assert_eq!(eval("-3-5"), Ok(Value::Int(-8)));
assert_eq!(eval("-5--3"), Ok(Value::Int(-2))); assert_eq!(eval("-5--3"), Ok(Value::Int(-2)));
assert_eq!(eval("5e2--3"), Ok(Value::Float(503.0)));
assert_eq!(eval("-5e-2--3"), Ok(Value::Float(2.95)));
} }
#[test] #[test]