0
    String a = "a*3";
    a = a.replace("a","45");

    // a contains 45*3

How do you I convert that to a DOUBLE which outputs 135.00 ??

Note : a can have any arthimetic operation... ( + , - , /)

Gowtham
  • 364
  • 2
  • 5
  • 16

1 Answers1

5

Simplest solution is to pass this off to Java's built in JavaScript engine.

public class Eval {

    public static void main(String[] args) throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");

        engine.put("a", 45);
        Number val = (Number) engine.eval("a*3");
        System.out.println(val.doubleValue());
    }
}
AJNeufeld
  • 8,526
  • 1
  • 25
  • 44