How can I divide the plots, adding only exact values for each plot, and a plot will be with an extra value?

Asked

Viewed 941 times

2

inserir a descrição da imagem aqui Example: The division of 100 (input value) by 3 (number of plots) is equal to 33.33, where 3 * 33.33 = 99.99. Being that the right is a portion with the value 33.34.

Java code

public void parcelar() {
    listaParcela = new ArrayList<>();
    //if (compra.getQtdparcelas() == null) {
    //   if (compra.getQtdparcelas() > 1) {
    Double totalP = compra.getValortotalentrada() / 
    compra.getQtdparcelas().doubleValue();
    DateTime data = new DateTime(pagar.getVencimento());
    for (int i = 1; i <= compra.getQtdparcelas(); i++) {
        Cpagar par = new Cpagar();
        par.setVencimento(data.toDate());
        par.setValor(totalP);
        par.setFormaPagamentoId(pagar.getFormaPagamentoId());
        par.setObs(campoconsulta);
        par.setContas(compra);
        compra.getContasList().add(par);
        listaParcela.add(par);
        data = data.plusMonths(1);
    }
}
  • Read more about floating point arithmetic, you can start with this question: https://answall.com/q/219211/64969

1 answer

4


I did it this way:

double diferenca = compra.getValortotalentrada() - (totalP * compra.getQtdparcelas().doubleValue());

Let’s assume that the value is 100 then the totalLP would be 33.33 as in your example.

The logic is as follows:

diferenca = 100  - (33.33 * 3)
diferenca = 100  - (99.99)
direfenta = 0.01

When entering the loop it adds this difference in the first installment:

par.setValor(totalP + diferenca);

And at the end not to add in the other attribute 0 in difference:

diferenca = 0;

Follow the example:

public void parcelar() {
    listaParcela = new ArrayList<>();
    //if (compra.getQtdparcelas() == null) {
    //   if (compra.getQtdparcelas() > 1) {
    Double totalP = compra.getValortotalentrada() / 
    compra.getQtdparcelas().doubleValue();
    DateTime data = new DateTime(pagar.getVencimento());
    double diferenca = compra.getValortotalentrada() - (totalP * compra.getQtdparcelas().doubleValue());
    for (int i = 1; i <= compra.getQtdparcelas(); i++) {
        Cpagar par = new Cpagar();
        par.setVencimento(data.toDate());
        par.setValor(totalP + diferenca);
        par.setFormaPagamentoId(pagar.getFormaPagamentoId());
        par.setObs(campoconsulta);
        par.setContas(compra);
        compra.getContasList().add(par);
        listaParcela.add(par);
        data = data.plusMonths(1);
        diferenca = 0;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.