Why is parseInt() not converting my String of numbers correctly?

断了今生、忘了曾经 提交于 2019-12-23 21:17:47

问题


I have some logic within a function that takes a string of numbers called digits like so:

6145390195186705543

I then attempt to convert with parseInt() like so:

parseInt(digits)

The result of:

digits = parseInt(digits);

is

6145390195186705000

Can someone help me understand why this is the case? and how i can get an accurate conversion?


回答1:


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?

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.


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.



来源:https://stackoverflow.com/questions/51215954/why-is-parseint-not-converting-my-string-of-numbers-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!