CKTIS / Java
math.MathContext: practical reference
math.MathContext: practical reference: MathContext combines decimal precision and rounding mode for BigDecimal operations; precision zero means unlimited.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.math.MathContextMathContext combines decimal precision and rounding mode for BigDecimal operations; precision zero means unlimited.
Use MathContext to pass a BigDecimal precision and RoundingMode explicitly to operations that must round under a defined decimal policy.
MathContext is not global and affects only operations that receive it. Precision zero means unlimited exact arithmetic, so its rounding mode is ignored.
A negative precision is invalid. RoundingMode.UNNECESSARY throws ArithmeticException when rounding would be needed, while DECIMAL32, DECIMAL64, and DECIMAL128 use HALF_EVEN.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var context = new java.math.MathContext(3, java.math.RoundingMode.HALF_UP);
System.out.println(new java.math.BigDecimal("1.2345", context));
}
}
Result
1.23
The example exercises the documented element in a small deterministic program and compares exact standard output.