1

My program takes a String input and calculates it using engine.eval() from ScriptEngine imports. How do I convert the evaluated value to type int?

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {

public static void main(String[] args) {

    String s = "206 + 4";
    Object eval;

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine eng = mgr.getEngineByName("JavaScript");

    try {
        eval = eng.eval(s);
    } catch (ScriptException e) {
        System.out.println("Error evaluating input string.");
    }

//Convert Object eval to int sum
}
}
flavian
  • 28,161
  • 11
  • 65
  • 105
Marco Lau
  • 579
  • 2
  • 10
  • 25

3 Answers3

1

You can convert it to a BigDecimal and then get the intValue() from it.

int val = new BigDecimal(eval.toString()).intValue();

Note that intValue() will trim the Decimal in the result. If you want to throw an exception, in case that is happening, use intValueExact() which throws an ArithmeticException.

Rahul
  • 44,383
  • 11
  • 84
  • 103
  • I have another question out of curiosity. Suppose I wanted to convert is to type long. How would this be achieved? – Marco Lau May 07 '13 at 10:26
  • 1
    That's where `BigDecimal` is the winner. Use `longValue()` instead of `intValue`. – Rahul May 07 '13 at 11:30
1

ScriptEngine returns Double for any arithmetic expression, so cast it to Double and use its intValue method

    int res = ((Double) eng.eval(s)).intValue();
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0
int i = Integer.valueOf((String) eval);