scaladoubletruncaterounding

Scala Doubles, and Precision


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


Solution

  • 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).