[Solved] Division Error: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

1. Background

Today, an error was encountered when calculating the inventory consumption percentage (consumed inventory/total inventory).Java.lang.arithmetexception: non terminating decimal expansion; no exact representable decimal result

Through the description of the exception, we know that this is because in some scenarios, for example, 1/3 will get an infinite decimal. At this time, it needs to be defined that the calculation result should be kept to a few digits after the decimal point, otherwise the above exception will be thrown.

2. Method introduction

The method used when an exception occurs. This method has no precision setting.

public BigDecimal divide(BigDecimal divisor) 

In the division operation, we need to use the following methods for accuracy control.

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

Attachment: don’t forget to judge whether the denominator is 0

3. The code is as follows

BigDecimal b1 = new BigDecimal(1);
BigDecimal b2 = new BigDecimal(3);
if (!Objects.equals(b2, BigDecimal.ZERO)) {
    // Cannot divide, mathematically infinitesimal, throws an ArithmeticException
    // BigDecimal b3 = b1.divide(b2);
    // Specify the precision of the calculation result, the number of decimal places to be retained, and the rounding mode
    BigDecimal b3 = b1.divide(b2, 4, BigDecimal.ROUND_HALF_UP);
    System.out.println(b3.toEngineeringString());
}

Similar Posts: