Search code examples
javadoubleroundingdivisionbigdecimal

BigDecimal divide method either returns 0 or ArithmeticException?


When I try dividing BigDecimals using the method:

divide(divisor, RoundingMode.HALF_UP)

it returns 0

enter image description here

But if I do it without a rounding mode like this:

divide(divisor)

I get an ArithmeticException

enter image description here

I don't care if the number is not an exact decimal representation. How do I divide BigDecimals without getting 0 or exceptions?


Solution

  • Use scale to divide BigDecimal.

      BigDecimal result = amount.divide(fromRate, 6, RoundingMode.HALF_UP);