Consider following code sample:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Tester {
public static void main( String[] args ) throws Exception {
ScriptEngine se = new ScriptEngineManager().getEngineByName( "nashorn" );
Object eval = se.eval( "5%5" );
System.out.println( "eval = " + eval );
System.out.println( "eval.getClass() = " + eval.getClass() );
}
}
Why it produces the following output?
eval = 0.0
eval.getClass() = class java.lang.Double
The result type is java.lang.Double
which is weird.
In case the remainder is different than 0 it correctly returns java.lang.Integer
, e.g. 5%2
returns java.lang.Integer' with value
1`.
Only 0 is somehow special.
Trying the same JavaScript expression in Firefox 32.0.2 (FindBugs console) works fine and returns plain 0.
Is there any way to force Nashorn to return Integer type instead of Double?
8u40 - forthcoming update - source http://hg.openjdk.java.net/jdk8u/jdk8u-dev/nashorn fixes this issue. That said, it is better to expect "java.lang.Number" (in the Java interface) type result for numerical calculations and convert using java.lang.Number methods like intValue(), doubleValue() etc.
There are no integers in JavaScript.
Start with ECMAScript Section 8: Types:
The ECMAScript language types are Undefined, Null, Boolean, String, Number, and Object.
Then see ECMAScript Section 8.5: The Number Type:
The Number type has exactly 18437736874454810627 (that is, 264−253+3) values, representing the double-precision 64-bit format IEEE 754 values ..." (emphasis added)
The fact that Firefox displays the floating point value 1 as "1" rather than "1.0" is irrelevant, and is confusing you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With