Search code examples
c#stringvariables.net-coreequation

Given a string to convert for a math equation with variable c# .net core


how can I convert a string to be an equation with variable avoiding function eval()?

I'm working on .net core and I have this

decimal total;
string var;

total = total + var;

but the string var is an equation with variable for now can be "1" or "total*2/100" but in future can be something else


Solution

  • You can't assign the result of equation to total because the equation may result into a decimal number and total is of type int.

    using System.Data;
    
    double result = Double.Parse(new DataTable().Compute($"{total}+{var.Replace("total", total+"")}", "")+"");
    

    the concatenations with an empty string is to convert the object returned by Compute() method to string and int type (total) to string because the Double.Parse() method and Replace() methods expect a string in their parameters.