2

Does someone know the best way to evaluate a string formula like this one: (123/2*15+22) within c#.

I have read that i should use an ICodeCompiled, but havent been able to find any good implementations to do this very simply thing.

Any suggestions are appreciated.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Morten Schmidt
  • 642
  • 8
  • 22

4 Answers4

9
class Program {
    static void Main(string[] args) {
        var calc = new System.Data.DataTable();
        Console.WriteLine(calc.Compute("(123/2*15+22)", ""));
        Console.ReadLine();
    }
}

Output: 944.5

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

I would take a look at MSDN's documentation on ICodeCompiler.

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
JC2
  • 141
  • 1
  • 4
  • 11
  • -1: I'm sorry, but this singularly unhelpful answer, you could make it marginally more helpful by providing a link to the documentation. P.s. I'll remove the downvote if you make the answer better. – Binary Worrier Feb 02 '11 at 16:33
0

You could use an expression parser, such as this one at CodeProject.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

For this type of problem I typically recommend FLEE; I've had nothing but good experiences using it to do equation evaluation and some basic DSL work.

Ron Warholic
  • 9,994
  • 31
  • 47