Search code examples
javascriptfloating-pointcomparison

JavaScript floating point curiosity


I tried doing some floating point comparison and here is what I found:

130 === 130.000000000000014210854715 // true
130 === 130.000000000000014210854716 // false
9 === 9.0000000000000008881784197001 // true
9 === 9.0000000000000008881784197002 // false
0.1 === 0.100000000000000012490009027033 // true
0.1 === 0.100000000000000012490009027034 // false

I tried running those on Firefox and Chrome with the same results. Okay, I KNOW that floating point comparison is a bad practice and has unexpected behavior. But I just curious about those numbers, why or how does those sequence of fractional digits calculated?

If you wish you could even expand those sequence further (kind of binary searching for the next sequence).


Solution

  • The fractional portion exceeds the precision of JavaScript's Number type.

    JavaScript can only handle the 130.0000000000000 portion of your number, so it becomes 130 (those 0s have no significance).

    Every Number in JavaScript is really a 64-bit IEEE-754 float, so the number 130.000000000000014210854715 will look like in binary...

    0,10000000110,10000010000000000000000000000000000000000000000000000
    

    Where the groups are sign (+ or -), exponent and significand/mantissa.

    You can see that the number 130 is the same...

    0,10000000110,10000010000000000000000000000000000000000000000000000 
    

    You'd need a 128 bit Number for JavaScript to be able to tell these two numbers apart, ot use a float128 implementation for JavaScript or bignum.