javascriptnode.jsbigintegerbigint

Node BigInt function shows the same for 2 different numbers


I am trying to calculate large numbers very accurately with nodejs and the BigInt function. But the BigInt function returns the same for 2 different numbers:

Input> BigInt(1320**2+25000000000000**2)
Output> 624999999999999973944983552n

Input> BigInt(25000000000000**2)
Output> 624999999999999973944983552n


Solution

  • You are trying to pass regular numbers to the BigInt() constructor and those regular numbers are subject to the regular number limitations before they even get to the BigInt constructor. You need to either pass strings, or if you want to do math on them, then you need to explicitly declare the numeric values as BigInt values first before doing the math on them.

    For example, you could do this:

    console.log(1320n ** 2n + 25000000000000n ** 2n)
    
    console.log(25000000000000n ** 2n)
    

    Which will give you:

    625000000000000000001742400n
    625000000000000000000000000n