Scala Doubles, and Precision

richsoni picture richsoni · Jun 19, 2012 · Viewed 122k times · Source

Is there a function that can truncate or round a Double? At one point in my code I would like a number like: 1.23456789 to be rounded to 1.23

Answer

Travis Brown picture Travis Brown · Jun 19, 2012

You can use scala.math.BigDecimal:

BigDecimal(1.23456789).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

There are a number of other rounding modes, which unfortunately aren't very well documented at present (although their Java equivalents are).