27

Possible Duplicates:
Is there a string math evaluator in .NET?
Converting string expression to Integer Value using C#
Best and shortest way to evaluate mathematical expressions
c# evaluating string “3*(4+2)” yield int 18

Is there a way to calculate math expressions like (2-3/4*12) in a different way than presented here?

http://www.c-sharpcorner.com/uploadfile/mgold/codedomcalculator08082005003253am/codedomcalculator.aspx

Community
  • 1
  • 1
gapo
  • 507
  • 1
  • 7
  • 19
  • http://stackoverflow.com/questions/333737/, http://stackoverflow.com/questions/234217/, http://stackoverflow.com/questions/1437964/, http://stackoverflow.com/questions/355062/ – Dour High Arch May 18 '10 at 16:27

7 Answers7

70

DataTable has a Compute method that allows you to write this:

var result = new DataTable().Compute("2-3/4*12", null);

Note that this is limited to simple math expressions.

Other option consist in using a dynamic language in the DLR such as IronPython and IronRuby. Check-out this post:

var engine = new IronPython.Hosting.PythonEngine();
double result = pythonEngine.EvaluateAs<double>("2-3/4*12");

You may also check the NCalc library on GitHub.

Mika Sundland
  • 14,170
  • 16
  • 31
  • 44
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
8

There are some interesting options available to you.

  1. NCalc - a C# Lexer Parser built with ANTLR. This will parse your text and allow you to assign values to parameters / variables. The interpreter is C#, so you do not have to load additional assemblies in an app domain, etc.

  2. JINT - a C# based Javascript interpreter built by the same author of ECalc using ANTLR to create the grammar. This is currently in beta but works well with calculations and functions.

  3. CS-Script.Net - From the site: "CS-Script is a CLR (Common Language Runtime) based scripting system which uses ECMA-compliant C# as a programming language. CS-Script currently targets Microsoft implementation of CLR (.NET 2.0/3.0/3.5) with limited support on Mono." The load scripts and create assemblies in memory and separate app domain. It is quite robust, and I use it in production for embedded scripting.

David Robbins
  • 9,964
  • 7
  • 47
  • 81
  • I second NCalc - i've used it extensively and found it very stable. – GreyCloud Dec 09 '10 at 09:34
  • On a different note, the NCalc guys have a C# javascript interpreter called Jint on codeplex.com I've played with it a little and can execute John Resig's original microtemplate.js with it. – David Robbins Dec 09 '10 at 19:15
4

Check out FLEE (Fast Lightweight Expression Evaluator) - http://flee.codeplex.com/

Flee is an expression parser and evaluator for the .NET framework. It allows you to compute the value of string expressions such as sqrt(a^2 + b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions directly to IL. This means that expression evaluation is extremely fast and efficient. Try out the demo, which lets you generate images based on expressions, and see for yourself.

It's free and fast and I've used it in a couple of projects.

Alex Warren
  • 6,132
  • 2
  • 26
  • 26
4

NB: This answer is just for completeness. It's definitely not an approach that I'd recommend.

It's possible to access the (deprecated) JScript libraries directly from C#, which means that you can use the equivalent of JScript's eval function.

using Microsoft.JScript;        // needs a reference to Microsoft.JScript.dll
using Microsoft.JScript.Vsa;    // needs a reference to Microsoft.Vsa.dll

// ...

string expr = "2 - 3 / 4 * 12";
Console.WriteLine(JScriptEval(expr));    // displays -7

// ...

public static VsaEngine _engine = VsaEngine.CreateEngine();

public static double JScriptEval(string expr)
{
    // error checking etc removed for brevity

    return double.Parse(Eval.JScriptEvaluate(expr, _engine).ToString());
}
LukeH
  • 242,140
  • 52
  • 350
  • 400
3

Definitely in the "do not recommend" category, but for completeness -- if you've got a database you can conveniently connect to, send it the query "SELECT expression".

Richard Dunlap
  • 1,855
  • 10
  • 14
0

Uh that seems like a very over the top solution.

What you really want is a simple parser.

You need to break the string up into tokens and then evaluate them. This will get you started researching. http://en.wikipedia.org/wiki/Parsing#Overview_of_process

James Van Boxtel
  • 2,285
  • 4
  • 22
  • 33
0

best option is to build Expression tree. First you build tree of your expression, then use http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx you can compile it then easily using http://msdn.microsoft.com/en-us/library/bb356928(v=VS.100).aspx

Andrey
  • 56,384
  • 10
  • 111
  • 154