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

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

    Number.MAX_VALUE will tell you the largest floating-point value representable in your JS implementation. The answer will likely be: 1.7976931348623157e+308. But that doesn't mean that every integer up to 10^308 can be represented exactly. As your example code shows, beyond 2^53 only even numbers can be represented, and as you go farther out on the number line the gaps get much wider.

    If you need exact integers larger than 2^53, you probably want to work with a bignum package, which allows for arbitrarily large integers (within the bounds of available memory). Two packages that I happen to know are:

    BigInt by Leemon

    and

    Crunch

提交回复
热议问题