-1

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

  • 1
    welcome to stackoverflow. i recommend [taking the tour](https://stackoverflow.com/tour), as well as reading [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [what's on topic](https://stackoverflow.com/help/on-topic). you _are_ encouraged to research things yourself. – Franz Gleichmann Nov 25 '21 at 17:28

1 Answers1

0

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.

Mustafa
  • 197
  • 1
  • 7