BigDecimal

来源:互联网 发布:任子行 酒店网络 编辑:程序博客网 时间:2024/06/14 19:55

BigDecimal介绍

BigDecimalJava提供的一个不变的、任意精度的有符号十进制数对象。它提供了四个构造器,有两个是用BigInteger构造,在这里我们不关心,我们重点看用doubleString构造的两个构造器

BigDecimal(double val)

          Translates a double into a BigDecimal.

BigDecimal(String val)

          Translates the String representation of a BigDecimal into a BigDecimal.


BigDecimal(double)是把一个double类型十进制数构造为一个BigDecimal对象实例。

BigDecimal(String)是把一个以String表示的BigDecimal对象构造为BigDecimal对象实例。


注意:这个构造器的结果可能会有不可预知的结果。有人可能设想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不可!


BigDecimal 舍入模式(Rounding mode)介绍:

BigDecimal定义了一下舍入模式,只有在作除法运算或四舍五入时才用到舍入模式,下面简单介绍,详细请查阅J2se API文档

static int

ROUND_CEILING

          Rounding mode to round towards positive infinity.

向正无穷方向舍入

static int

ROUND_DOWN

          Rounding mode to round towards zero.

向零方向舍入

static int

ROUND_FLOOR

          Rounding mode to round towards negative infinity.

向负无穷方向舍入

static int

ROUND_HALF_DOWN

          Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.

向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向下舍入例如1.55 保留一位小数结果为1.5

static int

ROUND_HALF_EVEN

          Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,如果保留位数是奇数,使用ROUND_HALF_UP ,如果是偶数,使用ROUND_HALF_DOWN

static int

ROUND_HALF_UP

          Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向上舍入, 1.55保留一位小数结果为1.6

static int

ROUND_UNNECESSARY

          Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.

计算结果是精确的,不需要舍入模式

static int

ROUND_UP

          Rounding mode to round away from zero.

向远离0的方向舍入


0 0
原创粉丝点击