0

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)"

?

Nethanek
  • 23
  • 6
  • Seems like it is a bug. Here is a question from 2 years ago about the very issue: http://stackoverflow.com/q/29255487/4996248 . That question links to this forum which suggests a workaround: https://ncalc.codeplex.com/discussions/346702 – John Coleman Apr 05 '17 at 18:42

1 Answers1

1

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:

Expression e = new Expression("3.1415 * 0.25");
double v = e.calculate();

Follow mXparser tutorial.

Regards

Leroy Kegan
  • 1,156
  • 10
  • 9
  • As in my post: `Abs(3.0) * Abs({0} + 34)`. I use `{0}` to insert double type value by `String.Format`. I'll take a look at mXparser - thanks. – Nethanek Apr 09 '17 at 03:14
  • Instead of {0} you can use user defined argument or user defined constant - i.e. http://mathparser.org/mxparser-tutorial/user-defined-arguments/ or http://mathparser.org/mxparser-tutorial/user-defined-constants/ – Leroy Kegan Apr 17 '17 at 09:07