简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM