C# – string math evaluator in .NET

cnet

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.

Best Answer

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.