Why is 9999999999999999 converted to 10000000000000000 in JavaScript?

后端 未结 5 2086
遥遥无期
遥遥无期 2020-11-30 03:45

Can any one explain to me why 9999999999999999 is converted to 10000000000000000?

alert(9999999999999999); //10000000000000000

http://jsfid

5条回答
  •  一整个雨季
    2020-11-30 04:19

    9999999999999999 is treated internally in JavaScript as a floating-point number. It cannot be accurately represented in IEEE 754 double precision as it would require 54 bits of precision (the number of bits is log2(9999999999999999) = 53,150849512... and since fractional bits do not exist, the result must be rouned up) while IEEE 754 provides only 53 bits (1 implict bit + 52 explicitly stored bits of the mantissa) - one bit less. Hence the number simply gets rounded.

    Since only one bit is lost in this case, even 54-bit numbers are exactly representable, since they nevertheless contain 0 in the bit, which gets lost. Odd 54-bit numbers are rounded to the nearest value that happens to be a doubled even 53-bit number given the default unbiased rounding mode of IEEE 754.

提交回复
热议问题