0

I'm trying to build a android calculator apps. I'll have some String such as "13+23-3" or "40*2+3". Is there a method can directly convert this kind of strings into double (with correct operator precedence)? Or i have to write a method myself?

I'd tried Double.parseDouble() and Double.valueOf() but both failed to convert it.

Luiggi Mendoza
  • 83,472
  • 15
  • 149
  • 315
user2236096
  • 1,437
  • 3
  • 12
  • 19

1 Answers1

0

You can use ScriptEngine class and use eval() function. I guess there may be a better way, but this will work, though not efficient certainly.

ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("js");        
Object result = e.eval("13+23-3");
AllTooSir
  • 47,910
  • 16
  • 124
  • 159