graaljs icon indicating copy to clipboard operation
graaljs copied to clipboard

Losing double type when returning 1.0 from JS

Open stas-panasiuk opened this issue 1 year ago • 1 comments

I have an application that runs JS code dynamically using Nashorn on Java 8. I'm migrating to GraalJS, but it seems that when you return 1.0 from JS, Nashorn returns Double 1.0, while GraalJS returns Integer 1.

Example Nashorn:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

...
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");

Map<String, Object> result = (Map<String, Object>) engine.eval("function test() {return { testInt: 1, testDouble: 1.0 } }; test();");

//works
assert result.get("testInt").equals(1);
//works
assert result.get("testDouble").equals(1.0);
...

Example GraalJS:

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Engine;
import org.graalvm.polyglot.Source;
import java.util.Map;

...
Engine engine = Engine.newBuilder().build();
try (Context context = Context.newBuilder().engine(engine).build()) {
    Source script = Source.create("js", "function test() {return { testInt: 1, testDouble: 1.0 } }; test();");

    Map<String, Object> result = (Map<String, Object>) context.eval(script).as(Map.class);

    //works
    assert result.get("testInt").equals(1);
    //doesn't work
    assert result.get("testDouble").equals(1.0);
}
...

pom.xml:

<dependency>
    <groupId>org.graalvm.sdk</groupId>
    <artifactId>graal-sdk</artifactId>
    <version>21.3.9</version>
</dependency>
<dependency>
    <groupId>org.graalvm.js</groupId>
    <artifactId>js</artifactId>
    <version>21.3.9</version>
    <scope>runtime</scope>
</dependency>

stas-panasiuk avatar Mar 11 '24 18:03 stas-panasiuk

Note that there is no difference between 1 and 1.0 in JavaScript. It is the same value. It is an implementation detail of Nashorn that it returns Integer in one case and Double in another. We are not going to mimic this detail. I suggest you not to depend on the exact type (in either JavaScript engine).

iamstolis avatar Mar 11 '24 21:03 iamstolis