Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# need to calculate formulae given as string expression.

john sal
Ranch Hand
Posts: 94
I have two String expression of a formulae like

String s = "max(1, 5)" ;

and
int a=2;
int b=2
String s2 = "a * b";

Is there any API in java which takes these string and calculate it as a mathematical expression?

Ulf Dittmer
Rancher
Posts: 42968
73
Search the FAQ pages for a library named JEP; it does this.

john sal
Ranch Hand
Posts: 94
It is not a freeware ...

Rob Spoor
Sheriff
Posts: 20708
68
• 1
If the formulas are not too complex you could try to use a JavaScript engine. See http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html for more information.

Edit: I just tried it, and it can handle a * b just fine:
The max function is undefined in JavaScript however. You can solve that by adding it as a function after line 8:
You may want to add a few similar functions like that, like min.

Also, the eval method returns a Double, but the cast to Number and then calling its intValue() method is a bit safer to get the int result.

Ulf Dittmer
Rancher
Posts: 42968
73
john sal wrote:It is not a freeware ...

It is, if you use the version linked in the JavaRanch FAQ (which is GPLed).

john sal
Ranch Hand
Posts: 94
can you please guide me to the link for GPLed as I am not able to find it..

Thanks.

john sal
Ranch Hand
Posts: 94
Hi Rob thanks a lot it worked fine and is vry helpful ..... Just have a doubt how can we make it work for the following expression?

"max(a,b)/c"

The only way i found is to send the c as well as an argument and do all the calculations in the method itself..is there any other possible and better way of doing this?

john sal
Ranch Hand
Posts: 94
Hey Rob thanks ... It is working fine for this expression as well.....I was executing it in a wrong way hence was not getting the expected result....

Thanks a lot

Rob Spoor
Sheriff
Posts: 20708
68
You're welcome