Converting string expression to Integer Value using C# [duplicate]
Sorry if this question is answered already, but I didn't find a suitable answer. I am having a string expression in C# which I need to convert to an int or decimal value.
For example:
string strExp = "10+20+30";
the output should be 60.
how shall I do that???
Use NCalc : stable, simple, and powerful
Fwiw, there is an expression parser built into the .NET framework. The DataTable.Compute() method uses it:
using System;
using System.Data;
class Program {
static void Main(string[] args) {
var expr = "10 + 20 + 30";
var result = new DataTable().Compute(expr, null);
Console.WriteLine(result);
Console.ReadLine();
}
}
Beware however that it isn't a very full-featured one. Simple expressions only, the kind you'd find in a SQL query.
There is nothing built into .NET, so you will need to use a mathematical expression parser and use that to get the result.
Here is one. And a couple of articles.