Scala BigDecimal.setScale
Scala BigDecimal supports decimal arithmetic and explicit rounding. setScale returns a value rounded to the requested number of decimal places.
A simple example
BigDecimal.setScale
- Start with 1.234
- Do this Round to two decimal places
- Result 1.23
Syntax
amount.setScale(2, BigDecimal.RoundingMode.HALF_EVEN)
Run this example in Scala
Save the program as Lesson.scala. Use Scala 2.13.
scalac Lesson.scala
scala Lesson
Round exact invoice amounts at decimal ties
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.
object Lesson {
def main(args: Array[String]): Unit = {
for (text <- List("2.005", "2.015")) {
println(BigDecimal(text).setScale(2, BigDecimal.RoundingMode.HALF_EVEN))
}
}
}
2.00 2.02
Constructing each amount from its decimal text preserves the tie. Half-even sends 2.005 to 2.00 and 2.015 to 2.02.
Scala documentation for BigDecimal.setScale
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.