1

What am I doing wrong here? Pretty sure this is right, I'm able to print the total, but then it breaks on calculating average.

public static void main(String[] args) {

    BigDecimal test1 = new BigDecimal("67");
    BigDecimal test2 = new BigDecimal("76");
    BigDecimal test3 = new BigDecimal("99");
    BigDecimal test_count = new BigDecimal("3");
    BigDecimal total = test1.add(test2).add(test3);
    System.out.println(total);
    BigDecimal average = total.divide(test_count);
    System.out.println(average);

}

Exception thrown:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
    at java.math.BigDecimal.divide(BigDecimal.java:1690)
    at HelloWorld.main(HelloWorld.java:31)
Max Weinzierl
  • 1,231
  • 10
  • 13
WhitneyChia
  • 746
  • 2
  • 11
  • 28
  • Can you update the console output also here – GrabNewTech Mar 06 '17 at 01:10
  • My console output is just the total, 242. It stops on the divide, which it doesn't like for some reason. Everything I see online says the syntax is right. I get an "arithmetic exception" on eclipse. It says BigDecimal.divide(BigDecimal) is not available. – WhitneyChia Mar 06 '17 at 01:13

1 Answers1

4

The ArithmeticException is thrown because your division leads to a non terminating decimal, if you explicitly provide the method with a rounding mode, this exception will no longer be thrown. So, try this

BigDecimal average = total.divide(test_count,  RoundingMode.HALF_UP);
JustDanyul
  • 13,813
  • 7
  • 53
  • 71
  • Thanks, that appears to be it. I will keep that in mind going forward, just thought it wasn't necessary since the documentation didn't say it was. – WhitneyChia Mar 06 '17 at 01:18
  • 1
    Official document also mentioned this point. Please refer to http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divide(java.math.BigDecimal) – GrabNewTech Mar 06 '17 at 01:19
  • This was the best answer that i read so far. It really explains why it fails. Thanks ! – tiagocarvalho92 May 12 '18 at 14:04