0

I have a string with values stored as:

string formula = "(10.5+10.5)/(2*5)";

double a=convert.ToDouble((10.5+10.5)/(2*5)) is working fine but i need to solve it like double a=convert.ToDouble(formula). Is it possible? I'm geeting error input string is not in correct format.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • 3
    This SO question has already answer for this http://stackoverflow.com/questions/333737/c-sharp-evaluating-string-342-yield-int-18 – J-D Dec 11 '15 at 05:48

1 Answers1

1

You cannot simply pass a formula to Convert.ToDouble and expect that it will calculate it. You need to compute the formula.

The good way is to implement a parser, which will build an expression tree, and calcultate the value.

Another hacky solution is to utilize Compute method of DataTable:

System.Data.DataTable table = new System.Data.DataTable();
decimal result = (decimal)table.Compute(formula);

Note that it returns decimal object. You can now use Convert to make it double, if you need:

double resultDouble = Convert.ToDouble(result);
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101