Search code examples
javascalabigdecimal

Can "java.lang.ArithmeticException: Rounding necessary" is detected before rounding?


java.math.BigDecimal generated by decimal string is sometimes available for setScale(n) but sometimes not.

scala> BigDecimal("1.00000000").setScale(1)
res0: scala.math.BigDecimal = 1.0

scala> BigDecimal("1.00000001").setScale(1)
java.lang.ArithmeticException: Rounding necessary

I know I can catch the exception on thrown, but is there any way to know if Rounding necessary or not before calling setScale?


Solution

  • I think you can set default rounding for setScale, like:

    BigDecimal("1.00000001").setScale(1, scala.math.BigDecimal.RoundingMode.HALF_DOWN)