Stacked Q&A

Java BigDecimal divide
  • 1 voting
  • 2022-06-26 00:00

    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);
        BigDecimal average = total.divide(test_count);

    Exception thrown:

    Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
        at java.math.BigDecimal.divide(
        at HelloWorld.main(

  • 2 2651 0 0
첨부 파일
총 2개의 답변이있습니다.
  • 답변일: 2022-06-26 00:00

    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);
  • 0 0 채택된 답변 퍼블 채택!