DEV Community

Discussion on: Working with extremely large numbers in JavaScript

Collapse
 
peerreynders profile image
peerreynders • Edited

What is wrong with BigInt? Available since Node.js 10.4.0 (2018) and caniuse.

console.assert((10000000000000001n + 1n).toString(), '10000000000000002');
console.assert((10000000000000002n - 1n).toString(), '10000000000000001');
console.assert((10000000000000002n * BigInt(3)).toString(), '30000000000000006');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ssadek1976 profile image
ssadek1976

When I tried to compute the below it gives me two different "k" constant values when they should be identical. See below results.
Iยดve also tried all bignumber libraries with the exact two differing results each time.

    // transaction
const tx0 = 2755738843649989653057n; // amount0Out BMON
const tx1 = 113747760332474227520n; // amount1In BUSD

// reserve after transaction
const x = 466822693713887341798087n; // reserve0 BMON
const y = 19334468154310748213608n; // reserve1 BUSD

// BigInt method
console.log("BigInt method...");
const k = x * y;
console.log("xy ", k); // 9025768505320715115682091222146517245881767896n

const newX = x + tx0;
const newY = y - tx1;
const newK = newX * newY;
console.log("xy ", newK); // 9025635755231009297480820885627169090307684672n
Enter fullscreen mode Exit fullscreen mode

Any ideas on how to resolve this issue in JavaScript would be greatly appreciated!