關於數據取捨問題的一個實例

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

相關文章
相關標籤/搜索