问题描述
在Java函数中具有“ long”变量。
public class LongToIntExample1{
public static void main(String args[]){
long l=2672558412L;
int i=(int)l;
System.out.println(i);
}
}
=>输出:-1622408884
module.exports.LongToIntExample1 = () => {
var l = 2672558412n;
var i = parseInt(l);
console.log(i);
}
=>输出:2672558412
解决方法
如果您阅读以下答案:https://stackoverflow.com/a/4355475/1725871 Java将包裹long
上方的Integer.MAX_VALUE
部分,其值将变为负数。
很明显,NodeJS并非如此
由于long大于int,因此您试图重现的行为实际上是Java实现不安全的双重结果,即不检查long值是否小于Integer.MAX_VALUE
我个人不会依赖程序中的机制
,我们可以使用内置的Int32Array将数字转换为32位带符号的整数,
function LongToIntExample1(num) {
return (new Int32Array([num]))[0];
}
console.log(LongToIntExample1(2672558412))
console.log(LongToIntExample1(2147483647))