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
  • 85,076
  • 16
  • 154
  • 332
user2236096
  • 1,537
  • 3
  • 13
  • 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
  • 48,828
  • 16
  • 130
  • 164