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:
- java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal …
- [Solved] BigDecimal division error: Non-terminating decimal expansion; no exact representable decimal result.
- [Solved] mapper.xml Error: java.lang.AbstractMethodError: Method oracle/jdbc/driver/OracleResultSetImpl.getNString(Ljava/lang/String;)Ljava/lang/String; is abstract,
- How to Solve TypeError: not all arguments converted during string formatting
- [Solved] Mvel user-defined function error: duplicate function
- How to Solve Error: Preflight response is not successful
- Java error: No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- LinAlgError: Last 2 dimensions of the array must be square
- [Solved] DOM parsing XML Error: Content is not allowed in prolog
- [Solved] Exception in thread “main” java.util.ConcurrentModificationException