问题描述
众所周知,Javascript在计算十进制数字时存在一些问题(或功能).例如:
As we know, Javascript has some issues (or features) with calculating decimal numbers. For example:
console.log(0.1 + 0.2) // 0.30000000000000004
我们知道我们可以使用不同的库来避免它(例如,我使用 bignumber.js ),现在我们有了预期的结果:
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>
但是
Bignumber.js具有局限性:
Bignumber.js has limitations:
我们可以传递一个字符串(可能),但是这样一来,我们可能会丢失一些数字:
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>
现在,我使用加密货币,并且经常处理像198.43092534959501
这样的数字,在这种情况下,我得到一个错误(如预期的那样):
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>
我知道有些人使用附加的乘法器,但是在上面提供的情况下将不起作用.如果您处理的是加密货币,那么您就会知道,我们实际上是在处理非乘和乘的值(例如489964999999000000
和0.489964999999
).但是我现在的目标是对不同货币的所有法定余额进行求和,但是它们具有不同的乘数,因此我不能只对未乘的值求和,并且看起来我需要以某种方式对乘后的值求和.
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:
如何求和/相乘/等十进制数字(超过15个数字)?
How to sum/multiply/etc. decimal numbers, which have more than 15 digits?
推荐答案
我已经在评论中回答了这个问题,但这是一个演示. BigNumber会接受字符串格式的数字作为输入.
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>
这篇关于计算Javascript中的大十进制数(超过15位数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!