Possible Duplicates:
Is there a string math evaluator in .NET?
Best and shortest way to evaluate mathematical expressions
I have a string variable
string exp = "12+34+4*56+(23*45+12)2/30"
what is the best way of doing it ? without the using of third party dll ?
How do you Write an Expression in Math? We write an expression in math by using numbers or variables and mathematical operators which are addition, subtraction, multiplication, and division. For example, the expression of the mathematical statement "4 added to 2", will be 2+4.
The basic operations (addition and subtraction) are used in different forms such as multiplication (repeated addition) and division (repeated subtraction). Using these operations, the word problems are modeled into math expressions.
You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.
You need a mathematical expression parser. The best way in my opinion is not reinventing the wheel. An existing open source solution NCalc is a good choice.
First translate it to an Expression Tree. If you use the built in Expression classes you get a compile method for free which gives you a compiled delegate, which thus is quite fast to evaluate. This is useful if you want to evaluate your expression for different parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With