I need to read from file mathematical expression and evaluate it's value. Example expression formats are as follow:
"5"- constant"3.1415 * 0.25"- constant expressions"{0} - 50"- expressions with value placeholders (String.Format())"Abs({0} - 50)"- just like up but with mathematical functions
I was using so far NCalc which worked great until it had to deal with expressions like follow:
"3.0 * Abs({0} + 34)"
Unfortunately in example just above the result of following code:
var value = ReadValueFromSomewhere(); // Lets say it returns 125.75
var exprStr = ReadExpression(); // returns: "3.0 * Abs({0} + 34)"
var toEval = String.Format(exprStr, value);
var result = new NCCalc.Expression(toEval).Evaluate()
is following exception:
System.InvalidOperationException
Operator '*' can't be applied to operands of types 'double' and 'decimal' NCalc.Numbers.Multiply(object, object) NCalc.Domain.EvaluationVisitor.Visit(NCalc.Domain.BinaryExpression) NCalc.Domain.BinaryExpression.Accept(NCalc.Domain.LogicalExpressionVisitor) NCalc.Expression.Evaluate()
It seems like Abs() method returns decimal and NCalc can't handle doing calculations between double and decimal (propably bug?). So I would like to ask what alternative libraries I could use instead of NCalc? Or perhaps there is other workaround than expression:
"Abs(3.0) * Abs({0} + 34)"
?
What do you mean by "expressions with value placeholders"? Can you give more specific example? You can try mXparser - it works for Java and .NET.
Example of usage:
Follow mXparser tutorial.
Regards