Jack Parker - 4 months ago 9

Java Question

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);

Answer

Tell `BigDecimal`

how you want to round when you do the `divide`

. Like this:

```
BigDecimal TotalPackageInt= cartQty.divide(cartMultiplier, 0, RoundingMode.UP );
```

Source (Stackoverflow)

Comments