regexp
regexp

Reputation: 263

Large integers in javascript (more the 2^53-1)

What is general principals to operate with large integers in javascript? Like in libraries for bigint? How i do it by myself?

Upvotes: 4

Views: 822

Answers (4)

You just use the JS-native BigInt (accepted into JS in 2019 and released as part of ES2020), which is a number primitive for working with integers that don't fit in the original Number type. In primitive form it uses the n suffix and works with all operators that regular numbers support, but with explicit integer logic. E.g. 1n/3n is 0n.

Also note that this is a different primitive from Number, so even for "safe" numbers the n version will not strictly equal the "plain" number:

const a = 1n;
const b = 1;
console.log(a === b); // false
try {
  console.log(a + b); // TypeError, you can't add a Number to a BigInt
} catch (e) {}
console.log(a + BigInt(b)); // 2n

Upvotes: 1

Don Albrecht
Don Albrecht

Reputation: 1302

Another option I've used in the past, is to hand off those operations to a calculation server via jsonp. If you're working with such large numbers, you likely want the improved performance and precision this can give you.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You may take a look at this implementation. You may also find other implementations useful.

Upvotes: 1

Related Questions