简体   繁体   English

JavaScript中一长串整数的转换问题

[英]Conversion issue for a long string of integers in JavaScript

I'm trying to convert a long string which has only integers to numbers. 我正在尝试将只有整数的长字符串转换为数字。

var strOne = '123456789123456789122';
parseInt(strOne, 10);
// => 123456789123456800000

var strTwo = '1234567891234567891232';
parseInt(strTwo, 10);
// => 1.234567891234568e+21

The expected output should be the same as strOne and strTwo but that isn't happening here. 预期的输出应该与strOnestrTwo相同, strOne不会发生。 While converting the string to a number, the output gets changed. 将字符串转换为数字时, output会发生变化。

What's the best way to fix this issue? 解决此问题的最佳方法是什么?

You number is unfortunately too large and gets wrapped when the conversion is done. 遗憾的是,您的号码太大,转换完成后会被包裹。

The largest integer you can express in JavaScript is 2^53-1 , it is given by Number.MAX_SAFE_INTEGER , see the MDN doc here . 您可以在JavaScript中表达的最大整数是2^53-1 ,它由Number.MAX_SAFE_INTEGER给出,请参阅此处MDN文档

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. 这个数字背后的原因是JavaScript使用IEEE 754中规定的双精度浮点格式数字,并且只能安全地表示 - (2 ^ 53 - 1)和2 ^ 53 - 1之间的数字。

 console.log(Number.MAX_SAFE_INTEGER); 

If you want to work with numbers bigger than this limit, you'll have to use a different representation than Number such as String and use a library to handle operations (see the BigInteger library for example). 如果要使用大于此限制的数字,则必须使用与Number类的不同表示形式(如String并使用库来处理操作(例如,请参阅BigInteger库 )。

BigInt is now available in browsers. 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. BigInt是一个内置对象,它提供了一种表示大于253的整数的方法,这是JavaScript可以用Number原语可靠表示的最大数字。

value The numeric value of the object being created. value正在创建的对象的数值。 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM