2

I have a problem related to the Numbers with Nashorn engine

Core problem is unable to receive a non decimal place number from Nashorn engine after rounding it using Math.round().

But it returns values with decimal places although within js it provides without decimal places and when I just return the harcoded primitive, it works fine.

How can I need to convert the floating point value to it's closest integer and receive it through the Nashorn. I know I can simply do return (num+"");. But I like to do it nicer and learn some new thing. Note : I want to do this with the js function.

script.js

var nonMath = function(){
    var num = 2; 
    print("num : " + num); //prints 2
    return (num);
};

var doMath = function(){
    var num = Math.round(2.0); 
    print("num : " + num); //prints 2
    return (num);
};

TestClass.java

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("lib/script.js"));

Invocable invocable = (Invocable) engine;
System.out.println("nonMath : " + invocable.invokeFunction("nonMath")); //prints 2
System.out.println("doMath : " + invocable.invokeFunction("doMath")); //prints 2.0
ironwood
  • 8,936
  • 15
  • 65
  • 114

1 Answers1

2

You can use ~~ to truncate the result of Math.round like

var doMath = function(){
    var num = ~~Math.round(2.0);
    return num;
}

which I ran with your code to get

doMath : 2
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249