问题描述
我必须计算一些浮点变量,我的同事建议我使用 BigDecimal
而不是 double
因为它会更精确.但我想知道它是什么以及如何充分利用 BigDecimal
?
I have to calculate some floating point variables and my colleague suggest me to use BigDecimal
instead of double
since it will be more precise. But I want to know what it is and how to make most out of BigDecimal
?
推荐答案
BigDecimal
是一种精确的数字表示方式.Double
有一定的精度.使用不同量级的双精度数(比如 d1=1000.0
和 d2=0.001
)可能会导致 0.001
在求和为差值时全部丢弃规模如此之大.使用 BigDecimal
这不会发生.
A BigDecimal
is an exact way of representing numbers. A Double
has a certain precision. Working with doubles of various magnitudes (say d1=1000.0
and d2=0.001
) could result in the 0.001
being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal
this would not happen.
BigDecimal
的缺点是速度较慢,而且以这种方式编写算法有点困难(由于 +
-
*
和 /
没有被重载).
The disadvantage of BigDecimal
is that it's slower, and it's a bit more difficult to program algorithms that way (due to +
-
*
and /
not being overloaded).
如果您要处理金钱,或者必须精确,请使用 BigDecimal
.否则双打
往往就足够了.
If you are dealing with money, or precision is a must, use BigDecimal
. Otherwise Doubles
tend to be good enough.
我建议您阅读 javadocBigDecimal 的 a> 因为他们确实比我在这里解释的更好:)
I do recommend reading the javadoc of BigDecimal
as they do explain things better than I do here :)
这篇关于Double 与 BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!