12

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???

CAbbott
  • 8,078
  • 4
  • 31
  • 38
Jankhana
  • 953
  • 4
  • 18
  • 29

5 Answers5

8

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
7

Use NCalc : stable, simple, and powerful

Catalin DICU
  • 4,610
  • 5
  • 34
  • 47
6

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

You'll need to parse the string by separating the numbers and the operators (+,-,*,/, etc.). The numbers can be converted to integers or decimals using the .TryParse commands (e.g. Int32.TryParse()). The operators can be handled with a switch statement. The more complicated the types of expressions you want to be able to handle the harder it's going to be. You could use recursion to handle sub-expressions in parentheses.

Edit: I was going to find some sample articles but I see that Oded has already posted some.

TLiebe
  • 7,913
  • 1
  • 23
  • 28
0

Perhaps use a scripting library - IronPython (python), cs-script (c#) or even MSScriptControl (VBscript) - you can then pass your string expression to the library for evaluation.

Example using MSScript Control:

using MSScriptControl;

...

ScriptControl ScriptEngine = new ScriptControlClass();

ScriptEngine.Language = "VBScript";

string expr = "10+20+30";

object result = ScriptEngine.Eval(expr);

decimal d = Convert.ToDecimal(result);

MZK
  • 1
  • A full scripting library can be dangerous and is usually the wrong choice, because that allows for a lot more than simple math expressions. – Joel Coehoorn Apr 09 '10 at 13:53