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) 
2
  • Can you update the console output also here Commented Mar 6, 2017 at 1: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. Commented Mar 6, 2017 at 1:13

1 Answer 1

6

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Official document also mentioned this point. Please refer to docs.oracle.com/javase/7/docs/api/java/math/…
This was the best answer that i read so far. It really explains why it fails. Thanks !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.