Why is JavaScript number * displayed * inaccurate for large numbers?

So in JavaScript, 111111111111111111111 == 111111111111111110000. Just enter any long number - at least 17 digits - to see it in action; -)

This is because JavaScript uses double precision floating point numbers, and some very long numeric literals cannot be accurately expressed. Instead, these numbers are rounded to the nearest representable number. See What is the highest JavaScript integer value that a number can go with without losing precision?

However, by doing the math according to IEEE-754, I found out that every number inside [111111111111111106560, 111111111111111122944] will be replaced with 111111111111111114752 inside. But instead of showing this number ... 4752, it displays as 111111111111111110000. So JavaScript shows these trailing zeros, which obfuscates the actual behavior. This is especially annoying because even numbers like 2 63, which represent accurately, get "rounded" as described.

So my question is, why does JavaScript behave like this when displaying a number ?

+3


source to share


1 answer


JavaScript integers can only be +/- 2 53 which:

9007199254740992

One of your numbers

111111111111111106560

which greatly exceeds the range of numbers that can be accurately represented as an integer.

This follows IEEE 754:



  • Sign bit: 1 bit
  • Exponent Width: 11 bits
  • Significant precision: 53 bits (52 explicitly stored)

EDIT

Displaying numbers is sometimes rounded by the JavaScript engine, yes. However, this can be overcome with a method toFixed

. (Warning, toFixed is known to break on some versions of IE).

In the console, enter:

111111111111111122944..toFixed(0)

      

"111111111111111114752"

+3


source







All Articles