Search code examples
scalatostringbigdecimal

What's the right way to drop trailing zeros of a BigDecimal in Scala?


scala.math.BigDecimal.toString can return something like "0.888200000". What can be the best I can do if I want "0.8882" instead? java.math.BigDecimal has stripTrailingZeros() method for this, but Scala's BigDecimal seems lacking it. Is using scala.math.BigDecimal.underlying to get the underlying java.math.BigDecimal the best way to go or is there a better way in Scala?


Solution

  • How about an implicit def if you want access to all the Java methods but don't want to type the underlying?

    val b = math.BigDecimal("0.888200000")
    implicit def bigDecimalToJavaBigDecimal(b: math.BigDecimal) = b.underlying
    
    scala> b.stripTrailingZeros
    res1: java.math.BigDecimal = 0.8882
    

    You get a Java BigDecimal back, but that's OK because there's already an implicit def back to the Scala version which you get when you import math.BigDecimal, called javaBigDecimal2bigDecimal.