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 轻帆向南 阅读(282) 评论(0)  编辑  收藏 所属分类: oj


只有注册用户登录后才能发表评论。


网站导航:
 

导航

留言簿

随笔分类(13)

随笔档案(13)

文章分类

最新评论