Why is 9999999999999999 converted to 10000000000000000 in JavaScript?

后端 未结 5 2084
遥遥无期
遥遥无期 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:31

    Why 9999999999999999 is converted to 10000000000000000 ?

    All numbers in JavaScript are stored in 64-bit format IEEE-754, also known as “double precision”, So there are exactly 64 bits to store a number: 52 of them are used to store the digits, 11 of them store the position of the decimal point (they are zero for integer numbers), and 1 bit is for the sign.

    If a number is too big, it would overflow the 64-bit storage, potentially giving an infinity:

    alert( 1e500 );  
    // Result => Infinity
    // "e" multiplies the number by 1 with the given zeroes count.
    

    If we check whether the sum of 0.1 and 0.2 is 0.3, we get false.

    alert( 0.1 + 0.2 == 0.3 )
    

    Strange! What is it then if not 0.3? This happens because, A number is stored in memory in its binary form, a sequence of ones and zeroes. But fractions like 0.1, 0.2 that look simple in the decimal numeric system are actually unending fractions in their binary form.

    In other words, what is 0.1? It is one divided by ten 1/10, one-tenth. In decimal numeral system such numbers are easily re-presentable. Compare it to one-third: 1/3. It becomes an endless fraction 0.33333(3).

    There’s just no way to store exactly 0.1 or exactly 0.2 using the binary system, just like there is no way to store one-third as a decimal fraction.

    The numeric format IEEE-754 solves this by rounding to the nearest possible number. These rounding rules normally don’t allow us to see that “tiny precision loss”, so the number shows up as 0.3. But beware, the loss still exists.

    As you see :

    alert( 9999999999999999 ); // shows 10000000000000000
    

    This suffers from the same issue: a loss of precision. There are 64 bits for the number, 52 of them can be used to store digits, but that’s not enough. So the least significant digits disappear.

    What is Really Happening behind 9999999999999999 to 10000000000000000 is :

    JavaScript doesn’t trigger an error in such events. It does its best to fit the number into the desired format, but unfortunately, this format is not big enough.

    Reference : https://javascript.info/number

    You can also refer this SO Question, it includes the very detail about the JavaScript Numbers.

提交回复
热议问题