Search code examples
javabigdecimal

BigDecimal division


I'm trying to use BigDecimal to calculate the GST tax rate.

The tax calculation is supposed to be 1/11 * item price.

So I thought I should probably use the BigDecimal to give the most accurate representation. But for some reason the rate is always calculated to zero.

this is what I've tried:

BigDecimal TAX_RATE = new BigDecimal("1")
    .divide(new BigDecimal("11"), BigDecimal.ROUND_HALF_UP);
BigDecimal bd = new BigDecimal("10").multiply(TAX_RATE);
// gives 0

Does anyone know why?


Solution

  • Try

    BigDecimal TAX_RATE = new BigDecimal("1").divide(new BigDecimal("11"), 500, BigDecimal.ROUND_HALF_UP);
    

    Second argument specifies precision. It's zero by default, so you end up rounding everything to an int.