java中的BigDecimal详解及使用

1 BigDecimal简介

BigDecimal是由任意精度的整数非标度值32位的整数标度 (scale) 组成。如果为零或正数,则标度是小数点后的位数。如果为负数,则将该数的非标度值乘以 10 的负scale 次幂。因此,BigDecimal表示的数值是(unscaledValue × 10-scale)
双精度浮点型变量double可以处理16位有效数。在实际应用中,需要对更大或者更小的数进行运算和处理。Javajava.math包中提供的APIBigDecimal,用来对超过16位有效位的数进行精确的运算

1.1 构造函数

1.1.1 构造API

BigDecimal类的主要构造器和方法

构造器 描述
BigDecimal(int) 创建一个具有参数所指定整数值的对象
BigDecimal(double) 创建一个具有参数所指定双精度值的对象
BigDecimal(long) 创建一个具有参数所指定长整数值的对象
BigDecimal(String) 创建一个具有参数所指定以字符串表示的数值的对象

1.1.2 使用

主要测试参数类型为doubleString的两个常用构造函数

BigDecimal adouble =new BigDecimal(1.22);
System.out.println("construct with a double value: " + adouble);
BigDecimal astring = new BigDecimal("1.22");
System.out.println("construct with a String value: " + astring);

输出结果会是什么呢?如果你没有认为第一个会输出1.22,那么恭喜你答对了,输出结果如下:

construct with a doublevalue:1.2199999999999999733546474089962430298328399658203125
construct with a String value: 1.22

JDK的描述:

  1. 参数类型为double的构造方法的结果有一定的不可预知性。有人可能认为在Java中写入new BigDecimal(0.1)所创建的BigDecimal正好等于 0.1(非标度值 1,其标度为 1),但是它实际上等于0.1000000000000000055511151231257827021181583404541015625
    这是因为0.1无法准确地表示为 double(或者说对于该情况,不能表示为任何有限长度的二进制小数)。这样,传入到构造方法的值不会正好等于 0.1(虽然表面上等于该值)。
  2. 另一方面,String 构造方法是完全可预知的:写入 new BigDecimal("0.1") 将创建一个 BigDecimal,它正好等于预期的 0.1。因此,比较而言,通常建议优先使用String构造方法。
  3. double必须用作BigDecimal的源时,请注意,此构造方法提供了一个准确转换;它不提供与以下操作相同的结果:先使用Double.toString(double)方法,然后使用BigDecimal(String)构造方法,将double转换为String。要获取该结果,请使用static valueOf(double)方法
  4. valueOf(doubleval)方法查看源码部分如下:

public static BigDecimal valueOf(double val) {
// Reminder: a zero double returns '0.0', so we cannotfastpath
// to use the constant ZERO. This might be important enough to
// justify a factory approach, a cache, or a few private
// constants, later.
return new BigDecimal(Double.toString(val));
}

1.2 方法

1.2.1 方法API

方法 描述
add(BigDecimal) BigDecimal对象中的值相加,然后返回这个对象
subtract(BigDecimal) BigDecimal对象中的值相减,然后返回这个对象
multiply(BigDecimal) BigDecimal对象中的值相乘,然后返回这个对象
divide(BigDecimal) BigDecimal对象中的值相除,然后返回这个对象
toString() 将BigDecimal对象的数值转换成字符串
doublue() 将BigDecimal对象中的值以双精度数返回
floatValue() 将BigDecimal对象中的值以单精度数返回
longValue() 将BigDecimal对象中的值以长整数返回
intValue() 将BigDecimal对象中的值以整数返回

1.2.2 加法操作

BigDecimal a =new BigDecimal("1.22");
System.out.println("construct with a String value: " + a);
BigDecimal b =new BigDecimal("2.22");
a.add(b);
System.out.println("aplus b is : " + a);

我们很容易会错误地认为输出:

construct with a Stringvalue: 1.22
a plus b is :3.44

但实际上a plus b is : 1.22
源码分析:
add(BigDecimal augend)方法

public BigDecimal add(BigDecimal augend) {
          long xs =this.intCompact; //整型数字表示的BigDecimal,例a的intCompact值为122
          long ys = augend.intCompact;//同上
          BigInteger fst = (this.intCompact !=INFLATED) ?null :this.intVal;//初始化BigInteger的值,intVal为BigDecimal的一个BigInteger类型的属性
          BigInteger snd =(augend.intCompact !=INFLATED) ?null : augend.intVal;
          int rscale =this.scale;//小数位数
          long sdiff = (long)rscale - augend.scale;//小数位数之差
          if (sdiff != 0) {//取小数位数多的为结果的小数位数
              if (sdiff < 0) {
                 int raise =checkScale(-sdiff);
                 rscale =augend.scale;
                 if (xs ==INFLATED ||
                     (xs = longMultiplyPowerTen(xs,raise)) ==INFLATED)
                     fst =bigMultiplyPowerTen(raise);
                }else {
                   int raise =augend.checkScale(sdiff);
                   if (ys ==INFLATED ||(ys =longMultiplyPowerTen(ys,raise)) ==INFLATED)
                       snd = augend.bigMultiplyPowerTen(raise);
               }
          }
          if (xs !=INFLATED && ys !=INFLATED) {
              long sum = xs + ys;
              if ( (((sum ^ xs) &(sum ^ ys))) >= 0L)//判断有无溢出
                 return BigDecimal.valueOf(sum,rscale);//返回使用BigDecimal的静态工厂方法得到的BigDecimal实例
           }
           if (fst ==null)
               fst =BigInteger.valueOf(xs);//BigInteger的静态工厂方法
           if (snd ==null)
               snd =BigInteger.valueOf(ys);
           BigInteger sum =fst.add(snd);
           return (fst.signum == snd.signum) ?new BigDecimal(sum,INFLATED, rscale, 0) :
              new BigDecimal(sum,compactValFor(sum),rscale, 0);//返回通过其他构造方法得到的BigDecimal对象
       }

以上只是对加法源码的分析,减乘除其实最终都返回的是一个新的BigDecimal对象,因为BigIntegerBigDecimal都是不可变的(immutable)的,在进行每一步运算时,都会产生一个新的对象,所以a.add(b);虽然做了加法操作,但是a并没有保存加操作后的值,正确的用法应该是a=a.add(b);

1.2.3 除法方法

1.2.3.1 引出问题

先看例子:

BigDecimal b1 = BigDecimal.ONE;
BigDecimal b2 = new BigDecimal("3");
System.out.println(b1.divide(b2));

以上代码运行时,可能会报错:java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
主要原因就是做除法运算时,没有除尽且没有对结果处理,就算术异常了

1.2.3.2 解决方法

1.2.3.2.1 方法一

divide方法第一个参数是除数,第二个参数是指定小数为数,第三个指定四舍五入规则
因此可以作如下修改:

System.out.println(b1.divide(b2,3,BigDecimal.ROUND_HALF_UP));
1.2.3.2.2 方法二

使用MathContext,其构造方法第一个是指定小数位数,第二个是指定四舍五入规则

MathContext mc = new MathContext(5, RoundingMode.HALF_UP);
System.out.println(b1.divide(b2,mc));

1.2.4 BigDecimal和格式化

public static void main(String[] args) {
double i = 3.856;
// 舍掉小数取整
System.out.println("舍掉小数取整:Math.floor(3.856)=" + (int) Math.floor(i));

// 四舍五入取整
System.out.println("四舍五入取整:(3.856)="+ new BigDecimal(i).setScale(0, BigDecimal.ROUND_HALF_UP));

// 四舍五入保留两位小数
System.out.println("四舍五入取整:(3.856)="+ new BigDecimal(i).setScale(2, BigDecimal.ROUND_HALF_UP));

// 凑整,取上限
System.out.println("凑整:Math.ceil(3.856)=" + (int) Math.ceil(i));

// 舍掉小数取整
System.out.println("舍掉小数取整:Math.floor(-3.856)=" + (int) Math.floor(-i));
// 四舍五入取整
System.out.println("四舍五入取整:(-3.856)=" + new BigDecimal(-i).setScale(0, BigDecimal.ROUND_HALF_UP));

// 四舍五入保留两位小数
System.out.println("四舍五入取整:(-3.856)="+ new BigDecimal(-i).setScale(2, BigDecimal.ROUND_HALF_UP));

// 凑整,取上限
System.out.println("凑整(-3.856)=" + (int) Math.ceil(-i));

1.3 精度不丢失原因

1.3.1 类介绍

首先来看一下BigDecimal的类声明以及几个属性:

public class BigDecimal extends Number implements Comparable<BigDecimal> {
    // 该BigDecimal的未缩放值
    private final BigInteger intVal;
    // 精度,可以理解成小数点后的位数
    private final int scale;
    // BigDecimal中的十进制位数,如果位数未知,则为0(备用信息)
    private transient int precision;
    // Used to store the canonical string representation, if computed.
    // 这个我理解就是存实际的BigDecimal值
    private transient String stringCache;
    // 扩大成long型数值后的值
    private final transient long intCompact;
}

1.3.2 例子入手

通过debug来发现源码中的奥秘是了解类运行机制很好的方式。请看下面的testBigDecimal方法:

@Test
public void testBigDecimal() {
    BigDecimal bigDecimal1 = BigDecimal.valueOf(2.36);
    BigDecimal bigDecimal2 = BigDecimal.valueOf(3.5);
    BigDecimal resDecimal = bigDecimal1.add(bigDecimal2);
    System.out.println(resDecimal);
}

在执行了BigDecimal.valueOf(2.36)后,查看debug信息可以发现上述提到的几个属性被赋了值:
在这里插入图片描述

接下来进到add方法里面,看看它是怎么计算的:

/**
 * Returns a BigDecimal whose value is (this + augend), 
 * and whose scale is max(this.scale(), augend.scale()).
 */
public BigDecimal add(BigDecimal augend) {
    if (this.intCompact != INFLATED) {
        if ((augend.intCompact != INFLATED)) {
            return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
        } else {
            return add(this.intCompact, this.scale, augend.intVal, augend.scale);
        }
    } else {
        if ((augend.intCompact != INFLATED)) {
            return add(augend.intCompact, augend.scale, this.intVal, this.scale);
        } else {
            return add(this.intVal, this.scale, augend.intVal, augend.scale);
        }
    }
}

看一下传进来的值:
在这里插入图片描述
进入上面代码块第8行的add方法:

private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {
    long sdiff = (long) scale1 - scale2;
    if (sdiff == 0) {
        return add(xs, ys, scale1);
    } else if (sdiff < 0) {
        int raise = checkScale(xs,-sdiff);
        long scaledX = longMultiplyPowerTen(xs, raise);
        if (scaledX != INFLATED) {
            return add(scaledX, ys, scale2);
        } else {
            BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);
            return ((xs^ys)>=0) ? // same sign test
                new BigDecimal(bigsum, INFLATED, scale2, 0)
                : valueOf(bigsum, scale2, 0);
        }
    } else {
        int raise = checkScale(ys,sdiff);
        long scaledY = longMultiplyPowerTen(ys, raise);
        if (scaledY != INFLATED) {
            return add(xs, scaledY, scale1);
        } else {
            BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);
            return ((xs^ys)>=0) ?
                new BigDecimal(bigsum, INFLATED, scale1, 0)
                : valueOf(bigsum, scale1, 0);
        }
    }
}

这个例子中,该方法传入的参数分别是:xs=236,scale1=2,ys=35,scale2=1

该方法首先计算scale1 - scale2,根据差值走不同的计算逻辑,这里求出来是1,所以进入到最下面的else代码块(这块是关键):

首先17行校验了一下数值范围,18行将ys扩大了10的n次倍,这里n=raise=1,所以返回的scaledY=350
接着就进入到20行的add方法:

private static BigDecimal add(long xs, long ys, int scale){
    long sum = add(xs, ys);
    if (sum!=INFLATED)
        return BigDecimal.valueOf(sum, scale);
    return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);
}

这个方法很简单,就是计算和,然后返回BigDecimal对象:
在这里插入图片描述

所以可以得出结论:BigDecimal在计算时,实际会把数值扩大10的n次倍,变成一个long型整数进行计算,整数计算时自然可以实现精度不丢失。同时结合精度scale,实现最终结果的计算。

posted @   上善若泪  阅读(1885)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示