parseInt changes the integer

一个人想着一个人 提交于 2019-12-10 10:52:27

问题


I am trying to pull a number (72157648141531978), which starts at the 21st character, out of the title of a page like so:

parseInt(document.title.substring(21), 10);  

This returns the string as an integer of 72157648141531980. I can't seem to figure out why it is changing the last two numbers. Any help would be appreciated.


回答1:


According to What is JavaScript's highest integer value that a Number can go to without losing precision? the max value of an integer is 9007199254740992.

I tried your calculation on http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_parseint and I can confirm your problem.

It looks like an issue parsing beyond this max value and it is rounding the last 2 figures.




回答2:


You have exceeded the limits of double-precision floating-point format, as used by JavaScript. You cannot use that precise number directly in JavaScript. You can use it as a string, but if you need to do arithmetic on it you will need a bignum library.



来源:https://stackoverflow.com/questions/26270598/parseint-changes-the-integer

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