peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

Loses precision when cast to native BigInt #210

Closed bwhrsc closed 4 years ago

bwhrsc commented 4 years ago
const BigInteger = require ('big-integer');

const bigInteger = BigInteger (98431810442228979385391258349711259686n);
const bigInt = BigInt (bigInteger);

console.log (bigInteger);
console.log (bigInt);

Output:

Integer { value: 98431810442228979385391258349711259686n }
98431810442228974157521554495426789376n

Environment:

bwhrsc commented 4 years ago

Workaround:

const bigIntFromString = BigInt (bigInteger.toString());
peterolson commented 4 years ago

You'll have to use the workaround because the .valueOf function of BigInt returns a JavaScript number, which removes precision. If you want to maintain precision you need to convert it to a string first.