This question already has an answer here:
Is there a way in Java to get the result from this mathematical expression:
String code = "5+4*(7-15)";
In other hand what's the best way to parse an arithmetic expression?
This question already has an answer here:
Is there a way in Java to get the result from this mathematical expression:
String code = "5+4*(7-15)";
In other hand what's the best way to parse an arithmetic expression?
There is no direct support in the Java SDK for doing this.
You will either have to implement it yourself (possibly using a parser generator such as JavaCC), or use an existing library.
One option would be JEP (commercial), another JEval (free software).
Probably not in as straight forward a manner as you are hoping!
But perhaps you could use a javax.script.ScriptEngine and treat the string as a ECMAScript expression, for example?
Take a look at: Scripting for the Java Platform.
There is no builtin way of doing that. But you can use one of the many many open source calculators available.
You can pass it to a BeanShell
bsh.Interpreter
, something like this:You'll want to ensure the string you evaluate is from a trusted source and the usual precautions but otherwise it'll work straight off.
If you want to go a more complicated (but safer) approach you could use ANTLR (that I suspect has a math grammar as a starting point) and actually compile/interpret the statement yourself.
You coul use that project
How to use:
There's a commercial tool called formula4j that does that job.
To take your example expression, it would be evaluated like this using formula4j:
Formula formula = new Formula("5+4*(7-15)");
Decimal answer = formula.getAnswer(); //-27