JSON解析将某些数字转换为其他数字

时间:2016-11-11 12:57:24

标签: javascript json

我发现通过parseInt时的某些号码正在更改为其他号码。

console.log( parseInt( 10153315281647662, 10 ) ); //10153315281647662
console.log( parseInt( 10153315281647663, 10 ) ); //10153315281647664
console.log( parseInt( 10153315281647664, 10 ) ); //10153315281647664
console.log( parseInt( 10153315281647665, 10 ) ); //10153315281647664
console.log( parseInt( 10153315281647666, 10 ) ); //10153315281647666
console.log( parseInt( 10153315281647667, 10 ) ); //10153315281647668
console.log( parseInt( 10153315281647668, 10 ) ); //10153315281647668
console.log( parseInt( 10153315281647669, 10 ) ); //10153315281647668
console.log( parseInt( 10153315281647660, 10 ) ); //10153315281647660


var str = '{ "id" : 10153315281647663 }';
console.log(  JSON.parse( str ) ) // id : 10153315281647664

我正在使用少量大数字parseInt或将str更改为JSON,其数字正在更改结果中的数字。这不是因为整数堆栈溢出,因为较大的数字10153315281647666正在解析而10153315281647663不正确,这可能是什么原因?

我已经通过将所有内容解析为字符串来修复了这个问题,但是这是什么原因?

2 个答案:

答案 0 :(得分:1)

您尝试解析的数字太大。它can't be reliably stored为双精度浮点



console.log(10153315281647663 > Number.MAX_SAFE_INTEGER);
console.log(10153315281647663);
console.log(Number.MAX_SAFE_INTEGER);




答案 1 :(得分:0)

无需解析数字,它只是最大可能位数的结束,而不会失去IEEE 754格式的精确度。



console.log(10153315281647662); //10153315281647662
console.log(10153315281647663); //10153315281647664
console.log(10153315281647664); //10153315281647664
console.log(10153315281647665); //10153315281647664
console.log(10153315281647666); //10153315281647666
console.log(10153315281647667); //10153315281647668
console.log(10153315281647668); //10153315281647668
console.log(10153315281647669); //10153315281647668
console.log(10153315281647660); //10153315281647660