MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.63k stars 743 forks source link

Is there any other way to handle new BigNumber(999999999999999999999) without using strings? #362

Closed Usualminds closed 7 months ago

Usualminds commented 8 months ago

The question is if we want to deal with large numbers like 999999999999999999999, can we ensure that its precision is not lost if we use any other JavaScript method?

Or we can only rely on the server to return a string instead of a number to handle this situation.

shuckster commented 8 months ago

When using Number, the precision is lost on construction.

There's no way to get a precise answer from a value that hits either UNSAFE or BFP limitations, because that precision cannot be stored in the first place.

If you wish to work with such numbers, you must use strings for both serialisation and business logic.

MikeMcl commented 8 months ago

@Usualminds

If you are asking if there is another way to transmit a big integer over a network without sending it as a string, then the answer is yes you can send it more compactly as an array of bytes.

You can convert a number, BigInt or BigNumber to binary or better hexdecimal, using .toString(16), then convert that to an array of bytes by filling a Uint8Array using parseInt(hex, 16) on each two hexadecimal characters.