That code will die a horrible death if the division has a non-terminating decimal expansion. See javadoc of divide(BigDecimal divisor)
:
if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException
is thrown.
Example:
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
one.divide(x); // throws java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
Use one of the other overloads of divide()
, e.g. divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
:
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 5, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.14286
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 30, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.142857142857142857142857142857