about BigDecimal

          在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不可!





           

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


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


          網站導航:
           

          導航

          留言簿

          隨筆分類(13)

          隨筆檔案(13)

          文章分類

          最新評論

          主站蜘蛛池模板: 乌拉特中旗| 墨玉县| 平湖市| 南华县| 措勤县| 柘荣县| 汤阴县| 固安县| 阿瓦提县| 夏邑县| 宜宾县| 苏尼特左旗| 九寨沟县| 阜城县| 蒙城县| 郑州市| 会东县| 岳池县| 从化市| 自贡市| 团风县| 景德镇市| 长汀县| 维西| 绵阳市| 临朐县| 凉城县| 金塔县| 连云港市| 孟村| 长葛市| 涿鹿县| 紫金县| 忻州市| 西平县| 陇西县| 海安县| 翁源县| 始兴县| 理塘县| 东城区|