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

后端 未结 5 1519
滥情空心
滥情空心 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:44

    Answering your second question, here is your maximum safe integer in JavaScript:

    console.log( Number.MAX_SAFE_INTEGER );
    

    All the rest is written in MDN:

    The MAX_SAFE_INTEGER constant has a value of 9007199254740991. The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2 ** 53 - 1) and 2 ** 53 - 1.

    Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.

提交回复
热议问题