Tony Tsui
Tony Tsui

Reputation: 21

How to use JavaScript to handle complex 100 digits (+/-) times 100 digits (+/-) multiplication without having an overflow error?

When I tried BigInt, the result returned a wrong result:

BigInt(123456789123456789*111111111111)
13717421013703702653171662848n

And this is what the actual result should be like by hand-written calculation:

13717421013703703578986282579

Is there a way to produce the correct result without this error? Thank you.

Upvotes: -1

Views: 181

Answers (1)

user12273078
user12273078

Reputation:

Instead of passing the multiplication to BigInt, convert both numbers to BigInt and multiply them after that:

const big = 123456789123456789n * 111111111111n;
console.log(big)

Note, use your browser's console, not the snippet's one (also, this won't work in Safari).

Upvotes: 2

Related Questions