1

I'm currently making a calculator using windows form and I'm using the string data type to store the math expression entered by the user. Except, when wanting to convert it to a data type which can give me the result I need to use an evaluator so I added the NCalc library to my project but it converts it to a double and I want it to give me a decimal as an output for precision reasons.

Is there any way to configure NCalc to perform computation in decimal instead of double? If not possible then what would be an efficient alternative?

    string expression = "2+4+36/12"
    double convertedExpression = Decimal.parse(expression);

It doesn't work this way but here is the idea of what I want. But it doesn't matter which way do I use to convert it I just want to convert a string wut==ith a mathematical expression to a decimal with the result of course.

KarimCool
  • 21
  • 3

1 Answers1

2

It looks like NCalc only supports parsing [int / double / string / datetime / bool] constants; Grammer/NCalc.g

You could define your own named function to do the conversion;

    var expr = new Expression("decimal(\"0.123\")");
    expr.EvaluateFunction += evaluateFunction;

    private void evaluateFunction(string name, FunctionArgs args){
        if (name == "decimal")
            arg.Result = decimal.Parse((string)args.Parameters[0].Evaluate());
        ...
    }
Jeremy Lakeman
  • 9,515
  • 25
  • 29
  • But even if I convert it to a decimal it's a double in the first place therefore I loose precision which I need because I want to make a calculator – KarimCool Nov 19 '19 at 17:39
  • Note that my example expression specified the value as a string constant. If you wanted to change the way numbers were parsed, you'd probably need to fork NCalc. – Jeremy Lakeman Nov 20 '19 at 00:48
  • You might want to consider using the C# Roslyn compiler instead https://blogs.msdn.microsoft.com/cdndevs/2015/12/01/adding-c-scripting-to-your-development-arsenal-part-1/ – Jeremy Lakeman Nov 20 '19 at 00:53