Reputation: 569
OK, so I'm trying to divide 2 random BigDecimal values. If the number is uneven or irregular rather than get the remainder, I would prefer to round it up to the nearest whole number. However, when I do this my website crashes and I get the following error.
Caused by: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
I would understand this happening if I hadn't been already rounding the digits, but because I am, I don't understand why this is happening.
BigDecimal cartQty= (testValue1).getQuantity().getValue();
BigDecimal cartMultiplier = (testValue2).getQuantity().getValue();
//below where it crashes so if 4/3 and the value is 1.333 I'd expect to get 2.
BigDecimal TotalPackageInt= cartQty.divide(cartMultiplier ).setScale(0, RoundingMode.UP);
Upvotes: 1
Views: 306
Reputation: 17924
Tell BigDecimal
how you want to round when you do the divide
. Like this:
BigDecimal TotalPackageInt= cartQty.divide(cartMultiplier, 0, RoundingMode.UP );
Upvotes: 3
Reputation: 77177
The fact that you understand the intent of the operations doesn't change the semantics of the actual Java method chain.
Your statement starts with cartQty
, then calls divide(cartMultiplier)
on it. Only after that returns is setScale(0, RoundingMode.UP)
called on its result. If the division throws an exception, then what you planned to do later doesn't matter.
Given that these are quantities, you might consider using BigInteger
instead of BigDecimal
.
Upvotes: 3