Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

evaluate an arithmetic expression stored in a string (C#)

Tags:

c#

I'm working on a application in C# in which I want to calculate an arithmetic expression that is given as a string. So like I got a string:

string myExpr="4*(80+(5/2))+2";

And I want to calculate the outcome of the arithmetic expression. While in a language such as Javascript, PHP etc. you could just use Eval to do the trick this doesnt seem to be an option in C#.

I suppose it is possible to write a code to devide it into countless simple expressions, calculate them and add them together but this would take quite some time and I'm likely to have lots of troubles in my attempt to do so.

So... my question, Is there any 'simple' way to do this?

like image 261
user6 Avatar asked Jan 06 '11 22:01

user6


3 Answers

There's a javascript library you can reference, then just do something like:

var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);

Edit; Library is Microsoft.JScript

like image 64
Rob Avatar answered Nov 15 '22 04:11

Rob


You could just call the JScript.NET eval function. Any .NET language can call into any other.

like image 27
Ben Voigt Avatar answered Nov 15 '22 03:11

Ben Voigt


Have you seen http://ncalc.codeplex.com ?

It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:

Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");

  e.Parameters["Pi2"] = new Expression("Pi * Pi");
  e.Parameters["X"] = 10;

  e.EvaluateParameter += delegate(string name, ParameterArgs args)
    {
      if (name == "Pi")
      args.Result = 3.14;
    };

  Debug.Assert(117.07 == e.Evaluate());

It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

It also supports logical operators, date/time's strings and if statements.

like image 44
GreyCloud Avatar answered Nov 15 '22 03:11

GreyCloud