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