Search code examples
stringscaladigits

String formatting according to number of decimal points


I want to write a string of variable values in a formatted way, according to the following:

Maximum decimal points is 3. If there are less than 3 significant points than less are written.

For example: the number 1.53848 will be written as 1.538 the number 1.0 will be written as 1 (rather than 1.000).

val variable1 = 1.
val variable2 = 1.53848
language = "%s average value is %.3f and %.3f".format(variable1, variable2)

Solution

  • This should do the trick:

    def format(d: Double) =
        BigDecimal(d).scale match {
            case x if x > 2 => "%.3f".format(d)
            case _ => d.toInt.toString
        }