MathContext Precision And Rounding

Control BigDecimal division precision with MathContext and rounding modes so non-terminating results never throw unexpectedly.

JavaData Integrity

Code

snippet
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class MathContextDemo {
    public static void main(String[] args) {
        BigDecimal amount = new BigDecimal("1234.5678");
        BigDecimal rate = new BigDecimal("0.0725");

        // DECIMAL64:16 位有效数字
        BigDecimal interest = amount.multiply(rate, MathContext.DECIMAL64);
        System.out.println("interest(16 digits): " + interest);

        // 自定义精度 6 位 + HALF_UP:金额常用口径
        MathContext money = new MathContext(6, RoundingMode.HALF_UP);
        System.out.println("amount / 3: " + amount.divide(new BigDecimal("3"), money));

        // 同一除法在不同舍入模式下的差异
        BigDecimal one = BigDecimal.ONE;
        BigDecimal three = new BigDecimal("3");
        System.out.println("HALF_EVEN: " + one.divide(three, new MathContext(6, RoundingMode.HALF_EVEN)));
        System.out.println("HALF_UP:   " + one.divide(three, new MathContext(6, RoundingMode.HALF_UP)));
        System.out.println("DOWN:      " + one.divide(three, new MathContext(6, RoundingMode.DOWN)));

        // 不带 MathContext 且除不尽时抛 ArithmeticException
        try {
            one.divide(three);
        } catch (ArithmeticException e) {
            System.out.println("no context: " + e.getClass().getSimpleName());
        }

        System.out.println("rounded: " + new BigDecimal("1.234567890123456789").round(MathContext.DECIMAL64));
    }
}

How the snippet works

The code’s whole job belongs to the class MathContextDemo and the function main.

Applying it

The run emits 7 labeled sections — interest(16 digits):, amount / 3:, HALF_EVEN:, HALF_UP:, DOWN:, no context:, rounded: — one per step.

Statements that matter

BigDecimal interest = amount.multiply(rate, MathContext.DECIMAL64);
MathContext money = new MathContext(6, RoundingMode.HALF_UP);
BigDecimal amount = new BigDecimal("1234.5678");

Interactive Tools for This Topic

FAQ

What does MathContext Precision And Rounding print when run?
Running the file directly is enough — expect labeled output lines such as `interest(16 digits):`, `amount / 3:`, `HALF_EVEN:`.