As we know, Javascript has some issues (or features) with calculating decimal numbers. For example:
console.log(0.1 + 0.2) // 0.30000000000000004
And we know that we can avoid it using different libraries (for example I use bignumber.js), and now we have what expected:
console.log(Number(new BigNumber(0.1).plus(0.2))); // 0.3
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/6.0.0/bignumber.min.js"></script>
BUT
Bignumber.js has limitations:
It accepts a value of type number (up to 15 significant digits only), string or BigNumber object.
We can pass a string (it's possible), but this way we can lost some digits from the end:
console.log(Number(new BigNumber(0.1).plus("198.43092534959501"))); // 198.530925349595, not 198.53092534959501
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/6.0.0/bignumber.min.js"></script>
Now I work with cryptocurrencies and often I deal with numbers like 198.43092534959501
, and in this case I get an error (as expected):
console.log(Number(new BigNumber(0.1).plus(198.43092534959501))); // error
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/6.0.0/bignumber.min.js"></script>
I know that some people uses additional multipliers, but it will not work in the case provided above. If you deal with cryptocurrencies, you know, that we actually work with non-multiplied and multiplied values (like 489964999999000000
and 0.489964999999
). But my goal for now is to sum all fiat balances for different currencies, but they have different multipliers, so I can't just sum non-multiplied values, and looks like I need to sum multiplied values somehow.
It was a small background, but my general question is:
How to sum/multiply/etc. decimal numbers, which have more than 15 digits?
I already answered this in the comment, but here's a demonstration. BigNumber will accept a number in string format for input.
console.log(new BigNumber(0.1).plus("198.43092534959501"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/6.0.0/bignumber.min.js"></script>
来源:https://stackoverflow.com/questions/49634774/calculate-large-decimals-more-than-15-digits-in-javascript