How to rent plots matching the total?

Asked

Viewed 78 times

2

     $meses = 3;
     $valor = 1000
     $valor_parcela = $valor  / $meses;

                for ($i = 1;$i <= $meses; $i++) {
                      $date_sum_month = date('d/m/Y', strtotime("+{$i} month", strtotime($date)));
                      array_push($boletos, ["numero" => $i, "vencimento" => date_sum_month, "valor" => $valor_parcela]);
                     }
return json_encode($boletos);

Result of my code:

1 - 333,333
2 - 333,333
3 - 333,333

Desired:

1 - 333
2 - 333
3 - 334
  • Use floor method: https://www.php.net/manual/en/function.floor.php

  • André, check if $valor_parcela = floor($valor / $meses); solves your problem if yes, explain to you in the answer

  • Luiz Augusto did, but the floor rounds to less. doc: floor - Round fractions down

1 answer

5


You need to make the difference of the sum of the rounded plots to zero houses and add in the last installment. So you want to do two things, calculate all the plots without the decimals, and then modify the last one to make sure that the sum of them is the same as the original value. Could do considering a certain number of decimal places, 1, 2 or even more, even if it exceeds the cents we use, just say how many houses you want to round.

$meses = 3;
$valor = 1000;
$boletos = [];
for ($i = 1; $i <= $meses; $i++) array_push($boletos, round($valor / $meses, 0));
$boletos[$meses - 1] += $valor - array_sum($boletos);
print_r($boletos);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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