Error in calculation

0

Hello, I'm having a project of a consortium calculator that is showing error. It receives the following data from the user:

  • Consortium value
  • Number of months
  • % of reserve fund
  • % of administrative fee

After this it calculates the value of the monthly installment.

My problem is this: If I put the amount of months 10 works if putting 15 already gives error.

Follow the code:

BigDecimal cota = new BigDecimal(jTextField1.getText());
BigDecimal prazo = new BigDecimal(jTextField2.getText());
BigDecimal reserva = new BigDecimal(jTextField3.getText());
BigDecimal adm = new BigDecimal(jTextField4.getText());

DecimalFormat decimal = new DecimalFormat("0.##");

//Calculo Fundo Comum
BigDecimal pc = new BigDecimal("100");
BigDecimal percentualMensal = pc.divide(prazo);
BigDecimal parcelaMensal = percentualMensal.multiply(cota);
BigDecimal parcelaMensal1 = parcelaMensal.divide(pc);

//Calculo Taxa Administrativa
BigDecimal a1 = adm.divide(prazo);
BigDecimal parcelaAdm = a1.multiply(cota);
BigDecimal parcelaAdm1 = parcelaAdm.divide(pc);

//Calculo Fundo Reserva
BigDecimal r1 = reserva.divide(prazo);
BigDecimal parcelaReserva = cota.multiply(r1);
BigDecimal parcelaReserva1 = parcelaReserva.divide(pc);

BigDecimal calculo = parcelaMensal1.add(parcelaAdm1.add(parcelaReserva1));

String a = decimal.format(calculo);

jLabel5.setText("Valor: "+a);
    
asked by anonymous 27.10.2017 / 21:19

1 answer

1

The problem has already been pointed out by @VitorStafusa in the comments, which is that the division results in an infinite periodic decimal, in the divide method.

If you consider a period of 15 months, the division you are doing is 100/15 that gives 6.6666666 infinitely.

Code problem example (with value 15 forced):

BigDecimal v1 = new BigDecimal(100);
BigDecimal v2 = new BigDecimal(15);     
BigDecimal v3 = v1.divide(v2);

System.out.println(v3);

That generates an exception in the divide method:

  

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

See the exception to occur in Ideone

Solution

The solution to this problem is actually simple. You only need to change your call to the divide method, indicating in how many decimal places the result and the rounding mode:

BigDecimal v3 = v1.divide(v2, 4, RoundingMode.HALF_UP);
//casas decimais--------------^ ,  ^-------- modo de arredondamento

See this example on Ideone

You have 3 rounding modes at your disposal:

  • HALF_DOWN
  • HALF_UP
  • HALF_EVEN
28.10.2017 / 00:46