What is the best way to do calculations on values in a string, for example: "(3.25 * 4) / 1.25 + 10"
-
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 Answers
You need to write math formula parser. If you don't want to write your own, check out this one

- 14,496
- 5
- 31
- 37
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.

- 3,030
- 5
- 32
- 47
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.

- 13,109
- 7
- 49
- 78