Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a string math evaluator in .NET?

Tags:

c#

.net

If I have a string with a valid math expression such as:

String s = "1 + 2 * 7";

Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.

like image 503
Guy Avatar asked Dec 10 '08 04:12

Guy


3 Answers

Strange that this famous and old question has not an answer that suggests the builtin DataTable.Compute-"trick". Here it is.

double result = Convert.ToDouble(new DataTable().Compute("1 + 2 * 7", null));

The following arithmetic operators are supported in expressions:

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)

More informations: DataColumn.Expression at Expression Syntax.

like image 113
Tim Schmelter Avatar answered Nov 14 '22 03:11

Tim Schmelter


You could add a reference to Microsoft Script Control Library (COM) and use code like this to evaluate an expression. (Also works for JScript.)

Dim sc As New MSScriptControl.ScriptControl()
sc.Language = "VBScript"
Dim expression As String = "1 + 2 * 7"
Dim result As Double = sc.Eval(expression)

Edit - C# version.

MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
sc.Language = "VBScript";
string expression = "1 + 2 * 7";
object result = sc.Eval(expression);            
MessageBox.Show(result.ToString());

Edit - The ScriptControl is a COM object. In the "Add reference" dialog of the project select the "COM" tab and scroll down to "Microsoft Script Control 1.0" and select ok.

like image 56
user21826 Avatar answered Nov 14 '22 04:11

user21826


For anybody developing in C# on Silverlight here's a pretty neat trick that I've just discovered that allows evaluation of an expression by calling out to the Javascript engine:

double result = (double) HtmlPage.Window.Eval("15 + 35");
like image 28
Guy Avatar answered Nov 14 '22 03:11

Guy