我遇到与 Nashorn 引擎的 Numbers 相关的问题
核心问题是使用 Math.round()
四舍五入后无法从 Nashorn 引擎接收非小数位数。
但它返回带有小数位的值,尽管在 js 中它提供了没有小数位的值,并且当我只返回编码原语时,它工作得很好。
我如何需要将浮点值转换为最接近的整数并通过 Nashorn 接收它。我知道我可以简单地执行 return (num+"")
; 。但我喜欢做得更好并学习一些新东西。
注意:我想用 js 函数来做到这一点。
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
最佳答案
您可以使用~~
chop Math.round
的结果,例如
var doMath = function(){
var num = ~~Math.round(2.0);
return num;
}
我用你的代码运行得到的
doMath : 2
关于javascript - 四舍五入后无法从 Nashorn 引擎接收非小数位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42451950/