Scala example: A function to round Double values to two decimals

As a little Scala example, here’s a function that converts a given Double value into a new Double value that has only two decimal places:

def formatToTwoDecimalPlaces(d: Double): Double =
    BigDecimal(d)
        .setScale(2, BigDecimal.RoundingMode.HALF_UP)
        .toDouble

As shown, the function does this by using Scala’s BigDecimal class.

Note that when you do something like this, you need to choose a rounding strategy, and in this function I have chosen the BigDecimal.RoundingMode.HALF_UP strategy. This results in functionality like this, as shown in the Scala REPL:

scala> formatToTwoDecimalPlaces(1.144)
val res0: Double = 1.14
                                                                                                                                            
scala> formatToTwoDecimalPlaces(1.145)
val res1: Double = 1.15
                                                                                                                                            
scala> formatToTwoDecimalPlaces(1.146)
val res2: Double = 1.15