JavaScript 中一长串整数的转换问题
Conversion issue for a long string of integers in JavaScript
我正在尝试将只有整数的长字符串转换为数字。
var strOne = '123456789123456789122';
parseInt(strOne, 10);
// => 123456789123456800000
var strTwo = '1234567891234567891232';
parseInt(strTwo, 10);
// => 1.234567891234568e+21
预期输出应与 strOne
和 strTwo
相同,但此处并未发生这种情况。将字符串转换为数字时,output
会发生变化。
解决此问题的最佳方法是什么?
不幸的是,您的数字太大,转换完成后被换行。
JavaScript可以表示的最大整数是2^53-1
,由Number.MAX_SAFE_INTEGER
给出,见MDN doc here.
The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2^53 - 1) and 2^53 - 1.
console.log(Number.MAX_SAFE_INTEGER);
如果你想处理大于这个限制的数字,你必须使用不同于 Number
的表示,例如 String
并使用库来处理操作(参见 the BigInteger library 例如)。
BigInt
现在可在浏览器中使用。
BigInt
is a built-in object that provides a way to represent whole
numbers larger than 253, which is the largest number JavaScript can
reliably represent with the Number primitive.
value The numeric value of the object being created. May be a string or an integer.
var strOne = '123456789123456789122';
var intOne = BigInt(strOne);
var strTwo = '1234567891234567891232';
var intTwo = BigInt(strTwo);
console.log(intOne, intTwo);
我正在尝试将只有整数的长字符串转换为数字。
var strOne = '123456789123456789122';
parseInt(strOne, 10);
// => 123456789123456800000
var strTwo = '1234567891234567891232';
parseInt(strTwo, 10);
// => 1.234567891234568e+21
预期输出应与 strOne
和 strTwo
相同,但此处并未发生这种情况。将字符串转换为数字时,output
会发生变化。
解决此问题的最佳方法是什么?
不幸的是,您的数字太大,转换完成后被换行。
JavaScript可以表示的最大整数是2^53-1
,由Number.MAX_SAFE_INTEGER
给出,见MDN doc here.
The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2^53 - 1) and 2^53 - 1.
console.log(Number.MAX_SAFE_INTEGER);
如果你想处理大于这个限制的数字,你必须使用不同于 Number
的表示,例如 String
并使用库来处理操作(参见 the BigInteger library 例如)。
BigInt
现在可在浏览器中使用。
BigInt
is a built-in object that provides a way to represent whole numbers larger than 253, which is the largest number JavaScript can reliably represent with the Number primitive.value The numeric value of the object being created. May be a string or an integer.
var strOne = '123456789123456789122';
var intOne = BigInt(strOne);
var strTwo = '1234567891234567891232';
var intTwo = BigInt(strTwo);
console.log(intOne, intTwo);