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
  • 665,005
  • 155
  • 1,345
  • 1,328
Morten Schmidt
  • 622
  • 7
  • 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
  • 897,808
  • 140
  • 1,634
  • 2,455
1

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

Robert Levy
  • 28,401
  • 6
  • 60
  • 93
JC2
  • 131
  • 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
  • 539,124
  • 75
  • 1,126
  • 1,354
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,894
  • 29
  • 47