tags:

views:

1460

answers:

9

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.

A: 

No, there is not.

JaredPar
+9  A: 

Not a built in one. But there is a pretty comprehensive one here.

Strelok
+10  A: 

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");
Guy
I wonder if you could reference this elsewhere. Probably not, but it would be cool.
Joel Coehoorn
+4  A: 

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.

A: 

You can use The expression evaluator (Eval function in 100% managed .NET)

jadsc
A: 

http://dotscript.com/Products/ExpressionEvaluator/

This runtime expression evaluator is exactly what you are looking for. It only costs $9.80 and you get the whole source code after purchasing. They also provide low-cost customizations to suit your specific preferences.

Blagovest Buyukliev
+2  A: 

Actually there is kind of a built in one - you can use the XPath namespace! Although it requires that you reformat the string to confirm with XPath notation. I've used a method like this to handle simple expressions:

    public static double Evaluate(string expression)
    {
        var xsltExpression = 
            string.Format("number({0})", 
                new Regex(@"([\+\-\*])").Replace(expression, " ${1} ")
                                        .Replace("/", " div ")
                                        .Replace("%", " mod "));

        return (double)new XPathDocument
            (new StringReader("<r/>"))
                .CreateNavigator()
                .Evaluate(xsltExpression);
    }
cbp
A: 

You can try Calculation Engine at calculator.codeplex.com

Tony Q