Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java 8 Nashorn (JavaScript) modulo returns 0.0 (double) instead of 0 (integer)?

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 value1`.

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?

like image 914
Piotr Nowicki Avatar asked Sep 23 '14 07:09

Piotr Nowicki


2 Answers

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.

like image 145
A. Sundararajan Avatar answered Sep 24 '22 13:09

A. Sundararajan


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.

like image 24
David P. Caldwell Avatar answered Sep 24 '22 13:09

David P. Caldwell