Convert string expression to Integer Value using C #

Sorry if this question has already been answered, but I did not find a suitable answer. I have a string expression in C # that I need to convert to an int or decimal value.

For example:

string strExp = "10+20+30"; 

the output should be 60.

how to do it?

+11
string c # integer
Apr 09 2018-10-09T00:
source share
5 answers

Use NCalc : Stable, Simple, and Powerful.

+6
Apr 09 '10 at 13:39 on
source share

Nothing is built into .NET, so you will need to use a mathematical expression analyzer and use it to get the result.

Here is one. And a couple of articles .

+6
Apr 09 '10 at 13:30
source share

Fwiw, there is an expression parser built into the .NET platform. 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 is not very fully functional. Simple expressions that you will find in an SQL query.

+5
Apr 09 '10 at
source share

You need to parse the string by separating numbers and operators (+, -, *, /, etc.). Numbers can be converted to integers or decimal numbers using .TryParse commands (for example, Int32.TryParse ()). Operators can be processed using the switch statement. The more complex the types of expressions you want to deal with, the harder it will be. You can use recursion to handle subexpressions in parentheses.

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

0
Apr 09 '10 at 13:30
source share

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

An example of 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);

0
Apr 09 2018-10-09T00:
source share



All Articles