标签:io ar 使用 sp for java on 数据 问题
BigDecimal
在《Effective Java》这本书中也提到这个原则,float和double只能用来做科学计算或者
是工程计算,在商业计算中我们要用 java.math.BigDecimal。BigDecimal一共有4个够造方
法,我们不关心用BigInteger来够造的那两个,那么还有两个,它们是:
BigDecimal(double val)
Translates a double into a BigDecimal.
BigDecimal(String val)
Translates the String repre sentation of a BigDecimal into a
BigDecimal.
上面的API简要描述相当的明确,而且通常情况下,上面的那一个使用起来要方便一些。我
们可能想都不想就用上了,会有什么问题呢?等到出了问题的时候,才发现上面哪个够造方
法的详细说明中有这么一段:
Note: the results of this constructor can be somewhat unpredictable. One might
assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal
to .1000000000000000055511151231257827021181583404541015625. This is so because
.1 cannot be represented exactly as a double (or, for that matter, as a binary
fraction of any finite length). Thus, the long value that is being passed in to
the constructor is not exactly equal to .1, appearances nonwithstanding.
The (String) constructor, on the other hand, is perfectly predictable: new
BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is
generally recommended that the (String) constructor be used in preference to
this one.
原来我们如果需要精确计算,非要用String来够造BigDecimal不可!在《Effective Java》
一书中的例子是用String来够造BigDecimal的,但是书上却没有强调这一点,这也许是一个
小小的失误吧。
标签:io ar 使用 sp for java on 数据 问题
原文地址:http://my.oschina.net/u/1455908/blog/356115