BigDecimal java.lang.ArithmeticException: Non-terminating decimal expansion; exception solution

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

Scene description

An exception occurred while writing a JAVA program today: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
The statement that found the error was:

buyMoney.divide(tradeMoney)

Solution

It turns out that if BigDecimal is used for division in JAVA, the second parameter must be passed in the divide method, and the definition is accurate to a few decimal places. Otherwise, if the result is an infinite loop decimal, the above will be thrown. abnormal.

 buyMoney.divide(tradeMoney,2, BigDecimal.ROUND_HALF_UP)

Source code

Note that the divide method of BigDecimal has two overloaded methods, one is to pass two parameters, the other is to pass three parameters:

Two-parameter method:

@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数

@param roundingMode rounding mode to apply. Incoming round mode

Three parameter method:

@param divisor value by which this {@code BigDecimal} is to be divided.
@param scale scale of the {@code BigDecimal} quotient to be returned.
@param roundingMode rounding mode to apply. Rounding in Pattern of

Follow me, more dry goods are waiting for you
Insert picture description here

Guess you like

Origin blog.csdn.net/CharlesYooSky/article/details/107928255