Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Losing double type when returning 1.0 from JS #808

Open
stas-panasiuk opened this issue Mar 11, 2024 · 1 comment
Open

Losing double type when returning 1.0 from JS #808

stas-panasiuk opened this issue Mar 11, 2024 · 1 comment

Comments

@stas-panasiuk
Copy link

stas-panasiuk commented Mar 11, 2024

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>
@iamstolis
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants