Library contents

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

  1. Start with 1.234
  2. Do this Round to two decimal places
  3. Result 1.23
The third decimal digit is 4. The hundredths digit stays at 3.

Syntax

Java 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.java

Round 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.

First output line2.00
Main.java
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));
        }
    }
}
Output
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.

Advertisements

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.

Given18.7 g → nearest whole gram
Worked result19 g

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.

Given6.2 → nearest whole count
Worked result6

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.

Documentation for BigDecimal.setScale