about BigDecimal

          在java中做大數(shù)運算時要用到BigDecimal類。
          何謂大數(shù)?
              單精度浮點數(shù):float--32位(4字節(jié))--有效數(shù)字7位;
              雙精度浮點數(shù):double--64位(8字節(jié))--有效數(shù)字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類型十進制數(shù)構造為一個BigDecimal對象實例。

          BigDecimal(String)是把一個以String表示的BigDecimal對象構造為BigDecimal對象實例。

          習慣上,對于浮點數(shù)我們都會定義為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)構造器是被優(yōu)先推薦使用的。

          看下面的結果:

               System.out.println(new BigDecimal(123456789.02).toString());

                System.out.println(new BigDecimal("123456789.02").toString());

          輸出為:

          123456789.01999999582767486572265625

          123456789.02

          現(xiàn)在我們知道,如果需要精確計算,非要用String來夠造BigDecimal不可!





           

          posted on 2012-02-15 16:50 輕帆向南 閱讀(304) 評論(0)  編輯  收藏 所屬分類: oj


          只有注冊用戶登錄后才能發(fā)表評論。


          網站導航:
           

          導航

          留言簿

          隨筆分類(13)

          隨筆檔案(13)

          文章分類

          最新評論

          主站蜘蛛池模板: 阿坝| 高唐县| 泰州市| 富锦市| 洪湖市| 从化市| 五莲县| 平湖市| 钟山县| 兴隆县| 安庆市| 乌海市| 水富县| 万州区| 枞阳县| 广饶县| 开封县| 翁源县| 雅安市| 和平县| 贵定县| 化州市| 葫芦岛市| 九龙坡区| 鸡西市| 连城县| 容城县| 乌恰县| 青神县| 临沂市| 吉木萨尔县| 江城| 湟源县| 苍山县| 德清县| 固始县| 元江| 大石桥市| 汉寿县| 正定县| 安溪县|