Reputation: 11639
I have some Scala division code like this:
order.price.toBigDecimal.round(MathContext.DECIMAL128) / order.subPrice.toBigDecimal).toString
That does not work. It throws me this error:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
I wrote this in return, but it does not round. It gives me a number like this: 9.8431984893148934
order.price.toBigDecimal.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble / order.subPrice.toBigDecimal.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
What can I do if the number I want returned from this division to have only two decimal places?
Upvotes: 1
Views: 932
Reputation: 7748
Your expression
order.price.toBigDecimal.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble / order.subPrice.toBigDecimal.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
is basically a division of a Double
by a Double
, which gives back a Double
with the exact result. I think what you're after might be
(order.price / order.subPrice).toBigDecimal.setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
which produces a number with 2 decimal places. Notice we round the result of the division and not the operands, so as not to lose precision.
Upvotes: 4