CKTIS / Java
RoundingMode — decimal rounding policies
java.math.RoundingMode specifies a rounding policy used by APIs such as BigDecimal. HALF_UP chooses the nearest value and breaks ties away from zero, including for negative numbers.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
value.setScale(newScale, RoundingMode.HALF_UP)java.math.RoundingMode is an enum specifying a rounding policy. RoundingMode.HALF_UP chooses the nearest value; ties go away from zero. At scale 2, 2.345 becomes 2.35, while -2.345 becomes -2.35.
UP rounds away from zero, DOWN toward zero, CEILING toward positive infinity, and FLOOR toward negative infinity. HALF_DOWN and HALF_EVEN choose the nearest value; ties go toward zero and toward an even last retained digit, respectively. UNNECESSARY requires an exact result; required rounding causes ArithmeticException.
For BigDecimal, setScale(2, RoundingMode.HALF_UP) specifies two decimal places, not two significant digits. BigDecimal is immutable: use the returned value. A string constructor such as new BigDecimal("2.345") preserves the exact decimal value; a constructor taking double can introduce effects of the number's binary representation.
The example compares HALF_UP with HALF_EVEN and shows that the original value remains unchanged. The documentation scope is Java SE 21; the production runtime is not attested.
Examples
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
BigDecimal positive = new BigDecimal("2.345");
BigDecimal negative = new BigDecimal("-2.345");
System.out.println(positive.setScale(2, RoundingMode.HALF_UP));
System.out.println(negative.setScale(2, RoundingMode.HALF_UP));
System.out.println(positive.setScale(2, RoundingMode.HALF_EVEN));
System.out.println(positive);
}
}Result
2.35 -2.35 2.34 2.345
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.