1

What is the best way to do calculations on values in a string, for example: "(3.25 * 4) / 1.25 + 10"

Ralf de Kleine
  • 11,464
  • 5
  • 45
  • 87
  • This has been featured on Stack Overflow: http://stackoverflow.com/questions/1384811/code-golf-mathematical-expression-evaluator-full-pemdas (I originally voted to close as a dupe of a different question, which was the wrong one and I can't change it now) – Greg Hewgill Sep 06 '09 at 19:34

3 Answers3

7

You need to write math formula parser. If you don't want to write your own, check out this one

http://www.codeproject.com/KB/cs/MathParserLibrary.aspx

Sorantis
  • 14,496
  • 5
  • 31
  • 37
1

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.

GreyCloud
  • 3,030
  • 5
  • 32
  • 47
0

Converting from infix to postfix notation is one way of solving this problem, as you can use a stack to parse and compute the expression.

There are a dozen solutions available online. Here's one of them.

Charlie Salts
  • 13,109
  • 7
  • 49
  • 78