0

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?

Richard G
  • 5,243
  • 11
  • 53
  • 95
  • Very minor nit, but something to keep in mind - BigDecimal.ONE and BigDecimal.TEN exist as constants. You may also find scaleByPowerOfTen ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#scaleByPowerOfTen(int))) to be useful rather than multiplying by ten. Though, thats not related to the issue you are having. –  Dec 13 '14 at 02:26
  • You will get more accurate results if you divide the item price by 11 rather than multiplying by a value that represents 1/11. That is because a `BigDecimal` cannot represent 1/11 (.090909090...) exactly, since your computer does not have enough memory to hold the entire repeating decimal. :) Ultimately, if the item price is big enough, you will get a rounding error. – ajb Dec 13 '14 at 02:29
  • Ok thanks, yeah I'll modify code to divide the price by 11, great idea. Michael - the "10" is just arbitrary, not related to the calculation, it's just a sample. Cheers. – Richard G Jan 07 '15 at 04:14

2 Answers2

1

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.

Dima
  • 39,570
  • 6
  • 44
  • 70
0

In your case TAX_RATE equals 0 because of BigDecimal.ROUND_HALF_UP. See http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP

Everv0id
  • 1,862
  • 3
  • 25
  • 47