Evaluate a String Expression

Problem

You want to evaluate a mathematical expression that is specified as a string (as in "2 + 3").

Solution

Create a component that wraps the expression evaluator provided with Microsoft JScript, and consume this component from any application that needs this functionality. Or, use the Microsoft Script Control COM component.

Discussion

The JScript .NET engine provides an expression evaluator that can evaluate a mathematical expression or any JScript code (including functions) in a string. Multiple lines can be separated with line-break characters. However, you can’t access this functionality directly from another language. Instead, you need to make a simple JScript wrapper to expose this functionality:

package JScriptUtil ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.