BigDecimal的使用

本文介绍了Java中用于高精度计算的BigDecimal类,详细阐述了其构造方法、运算规则,尤其是对除法运算中可能出现的非终止小数问题及解决办法。还探讨了BigDecimal的舍入模式,并展示了如何通过NumberFormat进行数值格式化。

一、什么是BigDecimal

Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。双精度浮点型变量double可以处理16位有效数。在实际应用中,需要对更大或者更小的数进行运算和处理。float和double只能用来做科学计算或者是工程计算,在商业计算中要用java.math.BigDecimal。BigDecimal所创建的是对象,我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。方法中的参数也必须是BigDecimal的对象。构造器是类的特殊方法,专门用来创建对象,特别是带有参数的对象。

二、构造方法

BigDecimal有四种构造方法:

BigDecimal bigDecimalInt = new BigDecimal(10);
BigDecimal bigDecimalDouble = new BigDecimal(9.7);
BigDecimal bigDecimalString = new BigDecimal("9.7");
BigDecimal bigDecimalLong = new BigDecimal(9L);

其中第二种不推荐使用,原因如下:

1、此构造函数的结果可能有些不可预测。人们可能会假设,在Java中编写新的BigDecimal(0.1)会创建一个完全等于0.1的BigDecimal值(未缩放的值为1,刻度为1),但它实际上等于0.10000000000000555115123125782702118158340451015625。这是因为0.1不能精确地表示为双精度(或者,就此而言,表示为任何有限长度的二进制分数)。因此,传入构造函数的值并不完全等于0.1,尽管存在外观。

2、另一方面,字符串构造函数是完全可预测的:编写新的BigDecimal(“0.1”)将创建一个完全等于0.1的BigDecimal。因此,通常建议优先使用字符串构造函数而不是此构造函数。

3、当双精度必须用作BigDecimal的源时,请注意此构造函数提供了精确的转换;它不会给出与使用double将double转换为字符串相同的结果。toString(double)方法,然后使用BigDecimal(String)构造函数。要获得该结果,请使用静态valueOf(double)方法。

我们输出一下上面四种构造的结果:

BigDecimal bigDecimalInt = new BigDecimal(10);
BigDecimal bigDecimalDouble = new BigDecimal(9.7);
BigDecimal bigDecimalString = new BigDecimal("9.7");
BigDecimal bigDecimalLong = new BigDecimal(9L);
System.out.println(bigDecimalInt);
System.out.println(bigDecimalDouble);
System.out.println(bigDecimalString);
System.out.println(bigDecimalLong);

结果如下:

10
9.699999999999999289457264239899814128875732421875
9.7
9

三、运算

对于常用的加,减,乘,除,BigDecimal类提供了相应的成员方法:

public BigDecimal add(BigDecimal value); //加法
public BigDecimal subtract(BigDecimal value); //减法
public BigDecimal multiply(BigDecimal value); //乘法
public BigDecimal divide(BigDecimal value); //除法

其中,加、减、乘没有什么需要注意的,需要注意的是除法divide。

会有一种情况,除不尽,商为无穷数,如果这种情况我们不注意的话,就会出现如下报错:

 BigDecimal bigDecimal1 = new BigDecimal("7");
 BigDecimal bigDecimal2 = new BigDecimal("3");
 BigDecimal bigDecimal3 = bigDecimal1.divide(bigDecimal2);
 System.out.println(bigDecimal3);

报错如下:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

我们看一下divide的源码会发现divide在BigDecimal中,除了上面使用的单个参数的一种外,还有下面三个参数的方法:

public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode);

第一个参数是除数,第二个参数是小数点保留的位数,第三个参数是舍入模式。
舍入模式一共有8种,源码中这样写:


    /**
     * Rounding mode to round away from zero.  Always increments the
     * digit prior to a nonzero discarded fraction.  Note that this rounding
     * mode never decreases the magnitude of the calculated value.
     */
    public final static int ROUND_UP =           0;

    /**
     * Rounding mode to round towards zero.  Never increments the digit
     * prior to a discarded fraction (i.e., truncates).  Note that this
     * rounding mode never increases the magnitude of the calculated value.
     */
    public final static int ROUND_DOWN =         1;

    /**
     * Rounding mode to round towards positive infinity.  If the
     * {@code BigDecimal} is positive, behaves as for
     * {@code ROUND_UP}; if negative, behaves as for
     * {@code ROUND_DOWN}.  Note that this rounding mode never
     * decreases the calculated value.
     */
    public final static int ROUND_CEILING =      2;

    /**
     * Rounding mode to round towards negative infinity.  If the
     * {@code BigDecimal} is positive, behave as for
     * {@code ROUND_DOWN}; if negative, behave as for
     * {@code ROUND_UP}.  Note that this rounding mode never
     * increases the calculated value.
     */
    public final static int ROUND_FLOOR =        3;

    /**
     * Rounding mode to round towards {@literal "nearest neighbor"}
     * unless both neighbors are equidistant, in which case round up.
     * Behaves as for {@code ROUND_UP} if the discarded fraction is
     * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
     * that this is the rounding mode that most of us were taught in
     * grade school.
     */
    public final static int ROUND_HALF_UP =      4;

    /**
     * Rounding mode to round towards {@literal "nearest neighbor"}
     * unless both neighbors are equidistant, in which case round
     * down.  Behaves as for {@code ROUND_UP} if the discarded
     * fraction is {@literal >} 0.5; otherwise, behaves as for
     * {@code ROUND_DOWN}.
     */
    public final static int ROUND_HALF_DOWN =    5;

    /**
     * Rounding mode to round towards the {@literal "nearest neighbor"}
     * unless both neighbors are equidistant, in which case, round
     * towards the even neighbor.  Behaves as for
     * {@code ROUND_HALF_UP} if the digit to the left of the
     * discarded fraction is odd; behaves as for
     * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
     * rounding mode that minimizes cumulative error when applied
     * repeatedly over a sequence of calculations.
     */
    public final static int ROUND_HALF_EVEN =    6;

    /**
     * Rounding mode to assert that the requested operation has an exact
     * result, hence no rounding is necessary.  If this rounding mode is
     * specified on an operation that yields an inexact result, an
     * {@code ArithmeticException} is thrown.
     */
    public final static int ROUND_UNNECESSARY =  7;

ROUND_UP:向远离0的方向舍入;
ROUND_DOWN:向0方向舍入;
ROUND_CEILING:向正无穷方向舍入;
ROUND_FLOOR:向负无穷方向舍入;
ROUND_HALF_UP:向距离最近的一方舍入,如果距离相等,向上舍入;
ROUND_HALF_DOWN:向距离最近的一方舍入,如果距离相等,向下舍入;
ROUND_HALF_EVEN:向距离最近的一方舍入,如果距离相等,根据保留位数的奇偶确定舍入方式,如果保留位数是奇数,向上舍入,如果保留位数是偶数,向下舍入;
ROUND_UNNECESSARY:计算结果是精确的,不需要舍入模式。

四、格式化

用NumberFormat类的format()方法对超出16位有效数字的货币值,百分值,以及一般数值进行格式化控制。DecimalFormat类也可以用来格式化BigDecimal,可以设置小数的位数,如下:

BigDecimal bigDecimal1 = new BigDecimal("8.54");
BigDecimal bigDecimal2 = new BigDecimal("0.855555");
DecimalFormat df = new DecimalFormat("0.0");
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance(); //建立百分比格式化用
percent.setMaximumFractionDigits(2); //百分比小数点最多2位
System.out.println(currency.format(bigDecimal1));
System.out.println(df.format(bigDecimal1));
System.out.println(df.format(bigDecimal2));
System.out.println(percent.format(bigDecimal2));

输出结果为:

8.54
8.5
0.9
85.56%
BigDecimal类是Java中处理高精度数值运算的强大工具,可执行精确的数学运算,避免浮点数的舍入误差,在金融和科学计算等需要高精度的场合不可或缺。以下是其常见使用方法: ### 初始化BigDecimal对象 可使用不同的构造方法来初始化。例如,使用`new BigDecimal(double)`和`new BigDecimal(String)`: ```java import java.math.BigDecimal; public class BigDecimalInitialization { public static void main(String[] args) { BigDecimal a = new BigDecimal(0.1); System.out.println("a values is:" + a); System.out.println("====================="); BigDecimal b = new BigDecimal("0.1"); System.out.println("b values is:" + b); } } ``` 这里使用`new BigDecimal(String)`能更精确地表示数值,因为`new BigDecimal(double)`可能会有舍入误差[^2]。 ### 基本数学运算 提供了一系列方法进行加法、减法、乘法和除法运算: ```java import java.math.BigDecimal; public class BigDecimalMathOperations { public static void main(String[] args) { BigDecimal num1 = new BigDecimal("130.512"); BigDecimal num2 = new BigDecimal("15.7"); // 加法 BigDecimal sum = num1.add(num2); System.out.println("加法结果: " + sum); // 减法 BigDecimal difference = num1.subtract(num2); System.out.println("减法结果: " + difference); // 乘法 BigDecimal product = num1.multiply(num2); System.out.println("乘法结果: " + product); // 除法(四舍五入保留2位小数) BigDecimal quotient = num1.divide(num2, 2, java.math.RoundingMode.HALF_UP); System.out.println("除法结果: " + quotient); } } ``` 上述代码展示了使用`add`、`subtract`、`multiply`和`divide`方法进行基本数学运算,除法时指定了保留小数位数和舍入模式[^1]。 ### 比较大小 通过`compareTo(BigDecimal)`方法来比较大小: ```java import java.math.BigDecimal; import org.junit.Test; public class BigDecimalComparison { @Test public void test4() { BigDecimal a = new BigDecimal("1"); BigDecimal b = new BigDecimal("2"); BigDecimal c = new BigDecimal("1"); int result1 = a.compareTo(b); int result2 = a.compareTo(c); int result3 = b.compareTo(a); System.out.println(result1); // -1 System.out.println(result2); // 0 System.out.println(result3); // 1 } } ``` 使用该方法时,若返回值为 -1 表示小于,0 表示等于,1 表示大于。需注意不能使用`equals`方法来比较大小,同时使用BigDecimal性能比`double`和`float`差,处理庞大、复杂运算时尤为明显,要根据实际需求选择使用哪种类型[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值