Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java BigDecimal.divide: make nonterminating quotients explicit

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

BigDecimal.divide without a rounding policy throws when the exact decimal quotient does not terminate.

Declare scale at the boundary

One unit split among three recipients has no finite decimal representation. A financial allocation must choose a scale and rounding mode, then decide how any remainder is assigned. Catching the exception and inventing a default amount would hide that policy.

The fixture rejects exact one-third division and then prints a two-decimal HALF_EVEN result. BigDecimal fundamentals cover text construction; UNNECESSARY rounding is useful when truncation must be rejected.

Reconcile the total

Three independently rounded shares of 0.33 add to 0.99, not 1.00. For money, allocate the remaining minor unit by an explicit rule rather than pretending the rounded quotient conserves the total.

Working program

Java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class SettlementSharePolicy {
    public static void main(String[] args) {
        BigDecimal settlement = new BigDecimal("1.00");
        BigDecimal recipients = new BigDecimal("3");
        try { settlement.divide(recipients); }
        catch (ArithmeticException rejected) { System.out.println("exact quotient unavailable"); }
        BigDecimal share = settlement.divide(recipients, 2, RoundingMode.HALF_EVEN);
        System.out.println("share=" + share);
        System.out.println("allocated=" + share.multiply(recipients));
    }
}

Output

Output
exact quotient unavailable
share=0.33
allocated=0.99

Cost and ownership

BigDecimal arithmetic allocates immutable results whose cost grows with operand precision. This small fixture is cheap; the material risk is losing a minor unit unless the allocation algorithm reconciles the rounded shares.

Common Mistakes

  • Do not call divide without a rounding policy for arbitrary ratios.
  • Do not assume independently rounded shares sum to the original amount.
  • Do not construct a declared decimal amount from an imprecise double.

Read next

Java BigDecimal: decimal amounts and explicit rounding, bigdecimal setscale unnecessary, Java BigDecimal equality: value and scale are separate contracts, Java DecimalFormat: reject trailing input and pin the locale.

java
numeric
bigdecimal-divide-rounding
Storage details