Search code examples
c#.netwinformscalculator

c# calculate multiple calculations from a string


I'm making a calculator in c# (winforms) and I was wondering if there is a simple way to calculate a string with multiple calculations in it so for example: if you have the string "124+241/2*5" let the program calculate it and then get an int output.

Thanks in advance.


Solution

  • Well, you're basically looking for the C# equivalent of Javascript's eval() function.

    I recommend the library NCalc.

    var result = new Expression("124+241/2*5").Evaluate()
    

    Another calculating engine would be Jace.NET.

    Dictionary<string, double> variables = new Dictionary<string, double>();
    variables.Add("var1", 2.5);
    variables.Add("var2", 3.4);
    
    CalculationEngine engine = new CalculationEngine();
    double result = engine.Calculate("var1*var2", variables);
    

    As of 2024, you may also look at Adletec.Sonic (sonic) which started as a fork of Jace.NET, which is no longer maintained. It can compile expressions dynamically for native execution for high performance.

    var expression = "var1*var2";
    
    var variables = new Dictionary<string, double>();
    variables.Add("var1", 2.5);
    variables.Add("var2", 3.4);
    
    var engine = Evaluator.CreateWithDefaults();
    double result = engine.Evaluate(expression, variables); // 8.5
    

    There's also Dynamic Expresso.

    var result = new Interpreter().Eval("124+241/2*5");
    

    And you can use Roslyn's ScriptingEngine to evaluate:

    Roslyn.Scripting.Session session = roslynEngine.CreateSession();
    session.Execute("124+241/2*5");