问题
So in JavaScript, 111111111111111111111 == 111111111111111110000. Just type any long number – at least about 17 digits – to see it in action ;-)
That is because JavaScript uses double-precision floating-point numbers, and certain very long numeric literals can not be expressed accurately. Instead, those numbers get rounded to the nearest representable number possible. See e.g. What is JavaScript's highest integer value that a Number can go to without losing precision?
However, doing the math according to IEEE-754, I found out that every number inside [111111111111111106560, 111111111111111122944] will be replaced by 111111111111111114752 internally. But instead of showing this ...4752 number, it gets displayed as 111111111111111110000. So JavaScript is showing those trailing zeros which obfuscates the real behavior. This is especially annoying because even numbers like 263, which are accurately representable, get "rounded" as described.
So my question is: Why does JavaScript behave like this when displaying the number?
回答1:
JavaScript integers can only be +/- 253, which is:
9007199254740992
One of your numbers is
111111111111111106560
which is considerably outside of the range of numbers that can accurately represented as an integer.
This follows the IEEE 754:
- Sign bit: 1 bit
- Exponent width: 11 bits
- Significand precision: 53 bits (52 explicitly stored)
EDIT
The Display of numbers is sometimes rounded by the JavaScript engine, yes. However, that can be over-ridden using the toFixed
method. (Warning, toFixed is known to be broken under some versions of IE).
In your console, type:
111111111111111122944..toFixed(0)
"111111111111111114752"
来源:https://stackoverflow.com/questions/25416544/why-is-javascripts-number-display-for-large-numbers-inaccurate