且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么parseInt()没有正确转换我的数字串?

更新时间:2023-12-05 11:18:52

这是破碎的浮点数学:Javascript使用64位来存储小到原子大小的数字,直到原子数为止宇宙由于这是一个相当宽的范围,它无法准确存储,因此数字以不精确的方式存储,但可以代表非常广泛的范围。在您的情况下 6145390195186705000 是JS能够存储的不准确版本,因为 6145390195186705543 无法存储。

This is another version of "broken" floating point math: Javascript uses 64 bits to store numbers as small as the size of an atom up to the number of atoms in the universe. As that is quite a broad range it cannot be stored accurately, therefore the numbers are stored in an imprecise way but can represent a very broad range. In your case 6145390195186705000 is the inaccurate version JS is able to store as 6145390195186705543 cannot be stored.


以及我如何获得准确的转换?

and how i can get an accurate conversion?

您无法存储准确数字,因此无法准确转换。但是,有些库允许您使用字符串,就像它们是数字一样,例如 BigIntJS

You cannot store an "accurate number", therefore you cannot convert it accurately. However there are some libraries that allow you to work with strings as if they were numbers, such as BigIntJS.

由于这是一个常见问题,这将在下一个JS版本中解决,请参阅提案。您现在可以在新版本的chrome中测试它。

As this is a common problem, this is going to be solved in the next JS version, see this proposal. You can currently test it in the new version of chrome.