Java BigDecimal.setScale
BigDecimal keeps decimal amounts exact when you construct them from text. setScale selects the number of decimal places and the rule for rounding.
A simple example
BigDecimal.setScale
- Start with 1.234
- Do this Round to two decimal places
- Result 1.23
Syntax
new BigDecimal(text).setScale(2, RoundingMode.HALF_EVEN)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRound a decimal invoice amount
A shop must print a decimal invoice total in cents. Apply the selected rounding rule to the original decimal amount so the printed charge can be reproduced during reconciliation.
import java.math.BigDecimal;
import java.math.RoundingMode;
class Main {
public static void main(String[] args) throws Exception {
for (String amount : new String[]{"2.005", "2.015"}) {
System.out.println(new BigDecimal(amount).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
2.00 2.02
Construct from the original decimal string. Half-even rounds a tie toward the even last digit, so amounts ending in .005 and .015 need not round in the same direction.
Round a parcel reading for a whole-unit display
A mailroom display shows only whole grams while its scale records tenths. A parcel weighs 18.7 grams and the display rounds to the nearest gram.
The reading lies closer to nineteen than eighteen.
Show a quiet hour on a dashboard
A sensor dashboard rounds the average number of entries to a whole count. This hour’s average is 6.2 so the designer checks what visitors will see.
The fraction is below one half, so the displayed whole count is six.
What to watch for
Choose the rounding rule required for the bill. Construct decimal prices from text or whole minor units.