在java中做大數運算時要用到BigDecimal類。
何謂大數?
單精度浮點數:float--32位(4字節)--有效數字7位;
雙精度浮點數:double--64位(8字節)--有效數字16位;
超過double表示范圍的,一律用BigDecimal。
關于BigDecimal的構造,需要從String構造,切記不可由double構造
即不可用 new BigDecimal(double var) [X]
而是通過 new BigDecimal(String var)
原因參考
http://hi.baidu.com/waiting__for__you/blog/item/967206ec863751d3b21cb170.html
【
BigDecimal(double)是把一個double類型十進制數構造為一個BigDecimal對象實例。BigDecimal(String)是把一個以String表示的BigDecimal對象構造為BigDecimal對象實例。
習慣上,對于浮點數我們都會定義為double或float,但BigDecimal API文檔中對于BigDecimal(double)有這么一段話:
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 .10000000000000000555111512312578 27021181583404541015625. 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 notwithstanding.
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
下面對這段話做簡單解釋:
注意:這個構造器的結果可能會有不可預知的結果。有人可能設想new BigDecimal(.1)等于.1是正確的,但它實際上是等于.1000000000000000055511151231257827021181583404541015625,這就是為什么.1不能用一個double精確表示的原因,因此,這個被放進構造器中的長值并不精確的等于.1,盡管外觀看起來是相等的。
然而(String)構造器,則完全可預知的,new BigDecimal(“.1”)如同期望的那樣精確的等于.1,因此,(String)構造器是被優先推薦使用的。
看下面的結果:
System.out.println(new BigDecimal(123456789.02).toString());
System.out.println(new BigDecimal("123456789.02").toString());
輸出為:
123456789.01999999582767486572265625
123456789.02
現在我們知道,如果需要精確計算,非要用String來夠造BigDecimal不可!
】