Reputation: 941
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?
Upvotes: 1
Views: 13215
Reputation: 9336
You can call BigDecimal.scale
, which will return the current scale of the BigDecimal.
Calling setScale
will throw an exception if the parameter is less than the current scale.
Upvotes: 1
Reputation: 14217
I think you can set default rounding for setScale
, like:
BigDecimal("1.00000001").setScale(1, scala.math.BigDecimal.RoundingMode.HALF_DOWN)
Upvotes: 7
Reputation: 33
You could do a modulo by 1 [0.1, 0.001] and check if the reminder is greater than 0
Upvotes: 0