CKTIS / Java
BigDecimal division with explicit scale and rounding
Use this `divide` overload to set the quotient’s scale and choose a rounding rule. The result has the requested scale even when the division is exact.
Version: Java SE 21
Syntax
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
BigDecimal quotient = dividend.divide(divisor, scale, roundingMode);BigDecimal.divide(divisor, scale, roundingMode) is an instance method: call dividend.divide(divisor, scale, roundingMode) to divide dividend by divisor. Both operands are java.math.BigDecimal values, and neither is modified. The int argument scale sets the result’s scale; the java.math.RoundingMode argument says how to round if needed.
A scale of 2 gives two places after the decimal point, including trailing zeros. A scale of 0 gives a whole-number result; a scale of -2 gives a multiple of 100. Scale is not the number of significant digits. HALF_UP chooses the nearest value at the requested scale, breaking ties away from zero.
Division by zero throws ArithmeticException. So does using UNNECESSARY when the exact quotient cannot be represented at the requested scale without rounding. The exact value 0.5 can be represented as 0.50 at scale 2 without changing its value.
divide(divisor, roundingMode) uses the dividend’s scale. divide(divisor) requires an exact result and throws if the decimal expansion does not terminate. divide(divisor, mathContext) uses the context’s precision and rounding mode instead of taking a target scale. The older overload that takes the rounding mode as an int is deprecated; use RoundingMode instead.
Examples
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
BigDecimal one = BigDecimal.ONE;
BigDecimal rounded = one.divide(BigDecimal.valueOf(8), 2, RoundingMode.HALF_UP);
BigDecimal exact = one.divide(BigDecimal.valueOf(2), 2, RoundingMode.HALF_UP);
System.out.println(rounded.toPlainString());
System.out.println(exact.toPlainString());
}
}Result
0.13 0.50
The exact quotient of `1 / 8` is `0.125`, so `HALF_UP` gives `0.13`. The quotient of `1 / 2` needs no rounding: `toPlainString()` prints `0.50`, keeping the trailing zero required by scale `2`.
Related lessons
- Java · Lesson 69 · Basic · Version: 2