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

3

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Expression syntax defined here: msdn.microsoft.com/en-us/library/…
7

Use NCalc : stable, simple, and powerful

Comments

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.

1 Comment

I like the codeproject's approach
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.

Comments

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);

1 Comment

A full scripting library can be dangerous and is usually the wrong choice, because that allows for a lot more than simple math expressions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.