Library contents

Groovy BigDecimal.setScale

Groovy decimal literals such as 2.005 are BigDecimal values. setScale returns a decimal rounded to the requested number of places.

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

Groovy syntax
amount.setScale(2, RoundingMode.HALF_EVEN)
Run this example in Groovy

Save the program as Lesson.groovy. Use Groovy 4 on the JVM.

groovy Lesson.groovy

Round a price under a specified tie rule

An invoice printer must turn line prices into a reproducible money total. Decide where rounding happens and which unit the accumulator stores before comparing the printed invoice with the ledger.

First output line2.00
Lesson.groovy
import java.math.RoundingMode

[2.005, 2.015].each { amount ->
    println amount.setScale(2, RoundingMode.HALF_EVEN)
}
Output
2.00
2.02

Half-even uses the nearest even retained digit on an exact tie. Keeping the amounts decimal throughout makes the two tie cases reproducible.

Java API documentation for BigDecimal.setScale

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.