关于数据取舍问题的一个实例

BigDecimal
在《Effective Java》这本书中也提到这个原则,float和double只能用来作科学计算或者
是工程计算,在商业计算中咱们要用 java.math.BigDecimal。BigDecimal一共有4个够造方
法,咱们不关心用BigInteger来够造的那两个,那么还有两个,它们是:java

BigDecimal(double val)app

         Translates a double into a BigDecimal.this

BigDecimal(String val)ci

         Translates the String repre sentation of a BigDecimal into a
BigDecimal.it

上面的API简要描述至关的明确,并且一般状况下,上面的那一个使用起来要方便一些。我
们可能想都不想就用上了,会有什么问题呢?等到出了问题的时候,才发现上面哪一个够造方
法的详细说明中有这么一段:io

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.table

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.sed

 

原来咱们若是须要精确计算,非要用String来够造BigDecimal不可!在《Effective Java》
一书中的例子是用String来够造BigDecimal的,可是书上却没有强调这一点,这也许是一个
小小的失误吧。float

相关文章
相关标签/搜索