2

JEXL evaluate returns int instead of float:

JexlEngine jexl = new JexlEngine();
Expression e = jexl.createExpression("7/2");
Float result = (Float)e.evaluate(null);

I receive this error:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float

Can I change a setting to return a float?

Andrew
  • 3,545
  • 4
  • 31
  • 37
  • can you try changing expression to `7/2.0` ? – jmj Dec 23 '14 at 20:01
  • Seems better, I get this now: java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float but I can convert it using result.floatValue(). Bummer though because now I have to create a method to add that decimal. – Andrew Dec 23 '14 at 20:08
  • try changing to `7/2.0F` – jmj Dec 23 '14 at 20:08

2 Answers2

3

7/2 expression will evaluate to int result and so it is failing to cast Integer to Float, if you want it to be resulting in float you need to change expression to 7 / 2.0F

jmj
  • 237,923
  • 42
  • 401
  • 438
1

To be accurate you must convert to Float any of your parameters, so use any of these (7 / 2F) or (7F / 2).

However, due to Java's auto-unboxing, your could avoid Exception in your initial code, but unfortunately lose in precision, if you use

Float result = (float)e.evaluate(null);

Another method that will work is casting to Double, so (7 / 2D) or (7D / 2) and then use

Float result = e.evaluate(null).floatValue();
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24