views:

541

answers:

6

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

A: 

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
+6  A: 

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
Thanks for the reply I will check and let you know.
Jankhana
I like the codeproject's approach
Jhonny D. Cano -Leftware-
+4  A: 

Use NCalc : stable, simple, and powerful

Catalin DICU
Hey it's great it worked. Thank youuuuuuuuuuuuuuuuuuuuu.
Jankhana
A: 

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
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
+3  A: 

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 dt = new DataTable();
    var result = dt.Compute("10+20+30", 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
A: 

This article did the trick for me. Pretty simple.

Jesse C. Slicer