Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Math calculator [duplicate]

Possible Duplicates:
Is there a string math evaluator in .NET?
Converting string expression to Integer Value using C#
Best and shortest way to evaluate mathematical expressions
c# evaluating string “3*(4+2)” yield int 18

Is there a way to calculate math expressions like (2-3/4*12) in a different way than presented here?

http://www.c-sharpcorner.com/uploadfile/mgold/codedomcalculator08082005003253am/codedomcalculator.aspx

like image 587
gapo Avatar asked May 18 '10 16:05

gapo


1 Answers

DataTable has a Compute method that allows you to write this:

var result = new DataTable().Compute("2-3/4*12", null); 

Note that this is limited to simple math expressions.

Other option consist in using a dynamic language in the DLR such as IronPython and IronRuby. Check-out this post:

var engine = new IronPython.Hosting.PythonEngine(); double result = pythonEngine.EvaluateAs<double>("2-3/4*12"); 

You may also check the NCalc library on GitHub.

like image 50
Darin Dimitrov Avatar answered Oct 04 '22 07:10

Darin Dimitrov