Search code examples
javascriptjava-8modulonashorn

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?


Solution

  • 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.