How javascript treat large integers (more than 52 bits)?

后端 未结 5 1569
滥情空心
滥情空心 2020-12-06 22:59

Consider this code (node v5.0.0)

const a = Math.pow(2, 53)
const b = Math.pow(2, 53) + 1
const c = Math.pow(2, 53) + 2

console.log(a === b) // true
console.         


        
5条回答
  •  青春惊慌失措
    2020-12-06 23:43

    How javascript treat large integers?

    JS does not have integers. JS numbers are 64 bit floats. They are stored as a mantissa and an exponent.

    The precision is given by the mantissa, the magnitude by the exponent.

    If your number needs more precision than what can be stored in the mantissa, the least significant bits will be truncated.

    9007199254740992; // 9007199254740992
    (9007199254740992).toString(2);
    // "100000000000000000000000000000000000000000000000000000"
    //  \        \                    ...                   /\
    //   1        10                                      53  54
    // The 54-th is not stored, but is not a problem because it's 0
    
    9007199254740993; // 9007199254740992
    (9007199254740993).toString(2);
    // "100000000000000000000000000000000000000000000000000000"
    //  \        \                    ...                   /\
    //   1        10                                      53  54
    // The 54-th bit should be 1, but the mantissa only has 53 bits!
    
    9007199254740994; // 9007199254740994
    (9007199254740994).toString(2);
    // "100000000000000000000000000000000000000000000000000010"
    //  \        \                    ...                   /\
    //   1        10                                      53  54
    // The 54-th is not stored, but is not a problem because it's 0
    

    Then, you can store all these integers:

    -9007199254740992, -9007199254740991, ..., 9007199254740991, 9007199254740992
    

    The second one is called the minimum safe integer:

    The value of Number.MIN_SAFE_INTEGER is the smallest integer n such that n and n − 1 are both exactly representable as a Number value.

    The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(253−1)).

    The second last one is called the maximum safe integer:

    The value of Number.MAX_SAFE_INTEGER is the largest integer n such that n and n + 1 are both exactly representable as a Number value.

    The value of Number.MAX_SAFE_INTEGER is 9007199254740991 (253−1).

提交回复
热议问题