Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 870
Ivan Avatar asked Dec 22 '22 02:12

Ivan


1 Answers

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.

like image 176
Luigi Plinge Avatar answered Jan 14 '23 13:01

Luigi Plinge