How to use String into Mathematical Expression or Generating dynamic Math formula from String.
Java 1.6 onward you can use JavaScript engine to convert String into Mathematical expression.
import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException; public class MathExpression{ calcualte() { ScriptEngineManager sem= new ScriptEngineManager(); ScriptEngine scEngine= sem.getEngineByName("JavaScript"); String formula = "30+50"; System.out.println(scEngine.eval(formula)); } }
Above code works fine for java. But JavaScript is not available in Android. so we have to use rhino in android.
dependencies { implementation 'io.apisense:rhino-android:1.0' }
import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException; public class MathExpression{ calcualte() { ScriptEngineManager sem= new ScriptEngineManager(); ScriptEngine scEngine= sem.getEngineByName("rhino"); String formula = "30+20"; System.out.println(scEngine.eval(formula)); } }