Search code examples
javascriptbigint

How can I print a BigInt in JavaScript without losing precision?


For example I have a long integer like BigInt(714782523241122198), is it possible to convert it to a string without losing any digits? I want to do it natively.


Solution

  • You have to either put an n after the number, or put it in quotes, since (as currently written) you have a Number, which is bigger than the max number representable in JavaScript, which is 2^53 or 9007199254740992.

    console.log(BigInt(714782523241122198).toLocaleString())
    console.log(BigInt("714782523241122198").toLocaleString())
    console.log((714782523241122198n).toLocaleString())

    To be clear, what you are currently doing is equivalent to:

    const x = 714782523241122198
    // x has already lost precision!
    const y = BigInt(x);
    // y was created with an imprecise number