CKTIS / Java
BigDecimal.setScale — changing scale and rounding
Set the scale of a `BigDecimal` while preserving its value or explicitly choosing how to round. The call does not change the original object.
Version: Java SE 21
Syntax
public BigDecimal setScale(int newScale)
public BigDecimal setScale(int newScale, RoundingMode roundingMode)
@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode)BigDecimal.setScale is an instance method on java.math.BigDecimal. A nonnegative scale counts places to the right of the decimal point; scale -1 represents multiples of ten. Scale is not precision (the number of digits in the unscaled value). The method returns a BigDecimal, not formatted text. The original is immutable, so use the return value; it need not be a newly allocated object.
setScale(int) preserves the numerical value. In decimal notation, increasing the scale can add trailing zeros, and an exact decrease can remove only zeros. If rounding would be needed, the method throws ArithmeticException.
setScale(int, RoundingMode) uses the chosen mode from java.math.RoundingMode when reducing the scale requires rounding. HALF_UP picks the nearest value at the target scale, with ties rounded away from zero: 2.675 becomes 2.68 at scale 2. UNNECESSARY requires an exact result and throws ArithmeticException if rounding is needed.
The setScale(int, int) overload has been deprecated since Java 9 and throws IllegalArgumentException if its second argument is not a valid rounding mode. Use the RoundingMode overload in new code. For exact decimal input, use new BigDecimal("2.675") rather than new BigDecimal(2.675), which captures the binary double approximation.
Examples
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
BigDecimal original = new BigDecimal("2.675");
BigDecimal padded = original.setScale(4);
System.out.println(padded.toPlainString());
System.out.println(padded.setScale(3).toPlainString());
System.out.println(original.setScale(2, RoundingMode.HALF_UP).toPlainString());
try {
original.setScale(2);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
}
System.out.println(original.toPlainString());
}
}Result
2.6750 2.675 2.68 ArithmeticException 2.675
The first two lines show a trailing zero being added and removed without changing the value. The third shows rounding, the fourth reports the caught exception, and the last shows the unchanged original.
Related lessons
- Java · Lesson 4 · Basic · Version: 2
- Java · Lesson 6 · Basic · Version: 2
- Java · Lesson 69 · Basic · Version: 2