### 1、 BigDecimal formatting

Because the format () method of numberformat class can use BigDecimal object as its parameter, BigDecimal can be used to format and control the currency value, percentage value and general value exceeding 16 significant digits.

Take the format of currency and percentage with BigDecimal as an example. First, create a BigDecimal object. After the arithmetic operation of BigDecimal, establish references to currency and percentage formatting respectively. Finally, use the BigDecimal object as a parameter of the format () method to output its formatted currency value and percentage.

```
@Test
public void test8(){NumberFormat currency = NumberFormat.getCurrencyInstance(); // Create currency formatting referenceBigDecimal money = new BigDecimal("15000.48"); // Contract amountSystem. Out. Println ("contract amount:"+currency.format(money));percent.format(taxRate)); currency.format(taxRateMoney));
}
```

result:

BigDecimal format, keep 2 as decimal, and supplement 0 if it is insufficient:

```
@Test
public void test9(){
System.out.println(formatToNumber(new BigDecimal("3.435")));
System.out.println(formatToNumber(new BigDecimal(0)));
System.out.println(formatToNumber(new BigDecimal("0.00")));
System.out.println(formatToNumber(new BigDecimal("0.001")));
System.out.println(formatToNumber(new BigDecimal("0.006")));
System.out.println(formatToNumber(new BigDecimal("0.206"))); String formatToNumber(BigDecimal obj) {
DecimalFormat df = new DecimalFormat("#.00");
if(obj.compareTo(BigDecimal.ZERO)==0) {
return "0.00";
}else if(obj.compareTo(BigDecimal.ZERO)>0&&obj.compareTo(new BigDecimal(1))<0){
return "0"+df.format(obj).toString();
}else {
return df.format(obj).toString();
}
}
```

The result is:

### 2、 BigDecimal common exception

#### 2.1. Division () is abnormal

When using the division function, set various parameters during divide, including divisor, exact decimal places and rounding mode, otherwise an error will be reported. The source code is as follows:

Note that the divide method of BigDecimal has two overloaded methods. One is to pass two parameters and the other is to pass three parameters:

Two parameter method:

@param divisor value by which this {@code BigDecimal} is to be divided. Incoming divisor

@Param rounding mode rounding mode to apply. The mode passed in to the round

Three parameter method:

@Param divisor value by which this {@ code BigDecimal} is to be divided

@Param scale of the {@ code BigDecimal} quote to be returned

@Param rounding mode rounding mode to apply. The mode passed in to the round

**Demo code:**

```
@Test
public void test10(){
BigDecimal Dividend = new BigDecimal("1");
BigDecimal divisor = new BigDecimal("3");
BigDecimal res1 = Dividend.divide(divisor,3,BigDecimal.ROUND_ UP);res1);
BigDecimal res2 = Dividend.divide(divisor,3,BigDecimal.ROUND_ DOWN);res2);
BigDecimal res3 = Dividend.divide(divisor,3,BigDecimal.ROUND_ CEILING);res3);
BigDecimal res4 = Dividend.divide(divisor,3,BigDecimal.ROUND_ FLOOR);res4);
BigDecimal res5 = Dividend.divide(divisor,3,BigDecimal.ROUND_ HALF_ UP);res5);
BigDecimal res6 = Dividend.divide(divisor,3,BigDecimal.ROUND_ HALF_ DOWN);res6);
BigDecimal res7 = Dividend.divide(divisor,3,BigDecimal.ROUND_ HALF_ EVEN);res7);
BigDecimal res8 = Dividend.divide(divisor,3,BigDecimal.ROUND_ UNNECESSARY);res8);
}
```

**Result display:**

**Cause analysis:**

Assert that the requested operation has a precise result and therefore does not need to be rounded. If this rounding mode is specified for an operation that obtains a precise result, an arithmeticexception is thrown.

#### 2.2. Division () is abnormal

`java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result`

**Cause analysis:**

In Java, if BigDecimal is used for division, the second parameter must be passed in the divide method, and the definition must be accurate to a few decimal places. Otherwise, if the result is an infinite circular decimal without integral division, the following exception will be thrown. java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

**resolvent:**

`a.divide(b, 2, BigDecimal.ROUND_HALF_UP);`

### 3、 Eight rounding modes of BigDecimal

```
@Test
public void test11(){
BigDecimal a = new BigDecimal("1.12345");
System.out.println("a = " + a);
BigDecimal b = a.setScale(4,BigDecimal.ROUND_HALF_DOWN);
System.out.println("b = " + b);
BigDecimal c = a.setScale(4,BigDecimal.ROUND_HALF_UP);
System.out.println("c = " + c);
}
```

#### 3.1、ROUND_UP

Rounding away from zero (rounding away from 0).

Always increase the number before discarding the non-zero part (always add 1 to the number before the non-zero discarding part).

Note that this rounding mode never reduces the size of the calculated value.

#### 3.2、ROUND_DOWN

Rounding mode near zero (rounding to zero).

Never increase the number before discarding a part (never increase the number before discarding a part by 1, i.e. truncate).

Note that this rounding mode never increases the size of the calculated value.

#### 3.3、ROUND_CEILING

Rounding pattern near positive infinity (rounding to positive infinity).

If BigDecimal is positive, the rounding behavior is the same as round_ Same as up;

If negative, the rounding behavior is the same as round_ Same as down.

Note that this rounding mode never reduces the calculated value.

#### 3.4、ROUND_FLOOR

Rounding pattern near negative infinity (rounding to negative infinity).

If BigDecimal is positive, the rounding behavior is the same as round_ Same as down;

If negative, the rounding behavior is the same as round_ Same as up.

Note that this rounding mode never increases the calculated value.

#### 3.5、ROUND_HALF_UP

Round to the “nearest” number. If the distance from two adjacent numbers is equal, it is the rounding mode of rounding up (rounding to the nearest side (distance), unless the two sides (distance) are equal. If so, round up, 1.55, one decimal place, and the result is 1.6).

If the discard part > = 0.5, the rounding behavior is the same as round_ Same as up; Otherwise, the rounding behavior is the same as round_ Same as down.

Note that this is the rounding pattern (rounding) that most of us learned in primary school.

#### 3.6、ROUND_HALF_DOWN

Round to the “closest” number. If the distance from two adjacent numbers is equal, it is the rounding mode of rounding up

(round to the nearest side, unless both sides are equal, if so, round down, for example, 1.55, keep one decimal place, and the result is 1.5).

If the discard part > 0.5, the rounding behavior is the same as round_ Same as up; Otherwise, the rounding behavior is the same as round_ Down is the same (rounded).

#### 3.7、ROUND_HALF_EVEN

Round to the “closest” number, or even if the distance from two adjacent numbers is equal.

If the number to the left of the discarded part is odd, the rounding behavior is the same as round_ HALF_ Same as up;

If it is an even number, the rounding behavior is the same as round_ HALF_ Same as down

Round to the nearest side unless both sides are equal. If so, use round if the number of reserved digits is odd_ HALF_ Up, if even, use round_ HALF_ DOWN）。

Note that this rounding mode minimizes cumulative errors when repeating a series of calculations.

This rounding model, also known as “banker rounding method”, is mainly used in the United States. To the nearest five.

If the previous digit is odd, it is rounded, otherwise it is rounded off.

The following example is the result of this rounding method if 1 decimal place is reserved.

1.15>1.2 1.25>1.2

#### 3.8、ROUND_UNNECESSARY

Assert that the requested operation has a precise result and therefore does not need rounding (the calculation result is accurate and does not need rounding mode).

If this rounding mode is specified for an operation that obtains a precise result, an arithmeticexception is thrown.

### 4、 BigDecimal summary

#### 4.1 summary

- BigDecimal is used when accurate decimal calculation is required. The performance of BigDecimal is worse than double and float, especially when dealing with large and complex operations. Therefore, BigDecimal is not necessary for general accuracy calculation.
- Try to use a constructor with a parameter type of string.
- BigDecimal is immutable. A new object will be generated every time four operations are performed, so remember to save the value after the operation when performing addition, subtraction, multiplication and division.

#### 4.2. Recommended tools

### 5、 Follow up blog

Remember to collect some waves o!!!

Blog home page:https://www.cnblogs.com/liyhbk/