一、什么是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%