Well, I did this class to solve your problem:
public final class PrecoComJuros {
private final BigDecimal valorBase;
private final BigDecimal valorParcelado; // pv
private final BigDecimal entrada;
private final int numeroParcelas;
private final BigDecimal taxaJuros;
private final BigDecimal valorParcela;
private final BigDecimal valorTotal; // pmt
private final BigDecimal valorJuros;
public PrecoComJuros(BigDecimal valorBase, BigDecimal entrada, int numeroParcelas, BigDecimal taxaJuros) {
if (numeroParcelas <= 0) throw new IllegalArgumentException();
if (taxaJuros.compareTo(BigDecimal.ZERO) < 0) throw new IllegalArgumentException();
this.valorBase = valorBase;
this.entrada = entrada;
this.numeroParcelas = numeroParcelas;
this.taxaJuros = taxaJuros;
BigDecimal juros = taxaJuros.divide(CEM); // i
this.valorParcelado = valorBase.subtract(entrada);
if (taxaJuros.compareTo(BigDecimal.ZERO) == 0) {
this.valorParcela = valorParcelado.divide(BigDecimal.valueOf(numeroParcelas), 2, RoundingMode.HALF_EVEN);
} else {
BigDecimal potencia = juros.add(BigDecimal.ONE).pow(numeroParcelas);
BigDecimal denominador = BigDecimal.ONE.subtract(BigDecimal.ONE.divide(potencia, 20, RoundingMode.HALF_EVEN));
this.valorParcela = valorParcelado.multiply(juros).divide(denominador, 2, RoundingMode.HALF_EVEN);
}
this.valorJuros = valorParcela.multiply(BigDecimal.valueOf(numeroParcelas));
this.valorTotal = entrada.add(valorJuros);
}
public BigDecimal getValorBase() {
return valorBase;
}
public BigDecimal getValorParcelado() {
return valorParcelado;
}
public BigDecimal getEntrada() {
return entrada;
}
public int getNumeroParcelas() {
return numeroParcelas;
}
public BigDecimal getTaxaJuros() {
return taxaJuros;
}
public BigDecimal getValorParcela() {
return valorParcela;
}
public BigDecimal getValorTotal() {
return valorTotal;
}
public BigDecimal getValorJuros() {
return valorJuros;
}
}
Here's her test:
public static void main(String[] args) {
System.out.println(Arrays.toString(" : : ".split(":")));
PrecoComJuros p = new PrecoComJuros(BigDecimal.valueOf(30_000), BigDecimal.valueOf(10_000), 24, BigDecimal.valueOf(5));
System.out.println("Valor da parcela: " + p.getValorParcela());
System.out.println("Juros total: " + p.getValorJuros());
System.out.println("Valor total: " + p.getValorTotal());
}
Some remarks about the implementation:
-
Passing a negative exponent to the pow
method causes an exception. The solution to this is to note that a ^ (- b) = 1 / (a ^ b) http://mathurl.com/ju3n77z.png , and therefore we can eliminate the need to use a negative exponent.
-
There is special treatment in case the interest rate is zero. If there was no such treatment, a division by zero would occur.
-
Values with zero or negative numbers or with negative interest rates are rejected.
-
The parcel value is calculated with cents accuracy (2 digits after the comma). Intermediate calculations, however use up to 20 boxes after the comma.