-1

Found this here:

enter image description here

How does this even work? What is happening here? Why does the number change in the first line?

Community
  • 1
  • 1
Bluefire
  • 13,519
  • 24
  • 74
  • 118
  • 1
    Downvoters should comment. – kemicofa ghost Aug 20 '15 at 13:01
  • 1
    JavaScript numbers are binary floating-point values with a limited precision. The first number is larger than the value of the largest exactly-representable integer. – Pointy Aug 20 '15 at 13:01
  • 4
    number is over Number.MAX_SAFE_INTEGER, related : http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin – Hacketo Aug 20 '15 at 13:02
  • And note that the exact same thing would happen (or, at least, *something* weird would happen) if you tried to use that number as a value in any language using 64-bit IEEE floating point. – Pointy Aug 20 '15 at 13:03
  • @Hacketo That only answers the last part of my question. – Bluefire Aug 20 '15 at 13:05
  • @GrimbodeI They probably think that the 'question does not show any research effort'. They might even go as far as thinking 'it is unclear or not useful'. That's what a downvote means per the title of the arrow. Why 'demand' a comment? see http://meta.stackoverflow.com/questions/252677/when-is-it-justifiable-to-downvote-a-question .. "downvote and move on". Not saying I agree or not (didn't vote) but it's certainly not necessary to comment... – Nanne Aug 20 '15 at 13:37

2 Answers2

3

JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1.

The number 111111111111111111 (18 digits) is above that range.

Reference: Number.MAX_SAFE_INTEGER

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

As mentioned above, JavaScript uses the double-precision 64-bit floating point format for the numbers. 52 bits are reserved for the values, 11 bits for the exponent and 1 bit for the plus/minus sign.

The whole deal with the numbers is beautifully explained in this video. Essentially, JavaScript uses a pointer that moves along the 52 bits to mark the floating point. Naturally, you need more bits to express larger numbers such as your 111111111111111111.

To convert your number into the binary, it would be

sign - 0
exponent - 10000110111
mantissa - 1000101010111110111101111000010001100000011100011100

The more space is taken by the value, the less is available for the decimal digits.

Eventually, simple calculations such as the increment by 1 will become inaccurate due to the lack of bits on the far right and the lowest possible increment will depend on the position of your pointer.

lmenus
  • 604
  • 9
  • 27