2

Possible Duplicate:
Addition for BigDecimal

I feel like I'm missing something obvious, but cannot figure out what it is. I'm trying to use BigDecimal to get the decimal portion of a division between two numbers. A very simple case, 1.00 divided by 3.00 should be 0.(3) repeating. However, I keep getting a result of 1.00.

BigDecimal num = new BigDecimal(1.00).setScale(2);
BigDecimal divisor = new BigDecimal(3.00).setScale(2);

num.divide(divisor, BigDecimal.ROUND_HALF_UP);

System.out.print(num);

My result is 1.00 and I can't figure out why?

Community
  • 1
  • 1

3 Answers3

14

The result of num.divide is ignored. You need to set that back into a variable

    BigDecimal num = new BigDecimal(1.00).setScale(2);
    BigDecimal divisor = new BigDecimal(3.00).setScale(2);

    BigDecimal result = num.divide(divisor, BigDecimal.ROUND_HALF_UP);

    System.out.print(result);

This prints 0.33

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
3

BigDecimals are immutable. You need to assign the result to the variable.

Honza Brabec
  • 37,388
  • 4
  • 22
  • 30
2

num.divide doesn't change num it returns the result.

Try:

num = num.divide(divisor, BigDecimal.ROUND_HALF_UP)
Peter Svensson
  • 6,105
  • 1
  • 31
  • 31