Skip to content
Advertisement

PHP creating lease calculator

I have a given an example by my customer for lease calculator that divides amount to 1 payment per 3 months. This is the sample:

THE AMOUNT is: 320.49 The payments are set to 4 payments

<table class="adm" width="100%"><thead><tr><th>Payment 1</th><th>Payment 2</th><th>Payment 3</th><th>Payment 4</th></tr></thead>
<tbody><tr><td><input class="short date mand" type="text" readonly="" name="vnoskadate[]" value="2019-10-17"></td>
<td><input class="short date mand" type="text" readonly="" name="vnoskadate[]" value="2020-01-16"></td>
<td><input class="short date mand" type="text" readonly="" name="vnoskadate[]" value="2020-04-16"></td>
<td><input class="short date mand" type="text" readonly="" name="vnoskadate[]" value="2020-07-16"></td></tr>
<tr><td><input class="short mand" type="text" name="vnoskasum[]" value="80.13"></td>
<td><input class="short mand" type="text" name="vnoskasum[]" value="80.13"></td>
<td><input class="short mand" type="text" name="vnoskasum[]" value="80.13"></td>
<td><input class="short mand" type="text" name="vnoskasum[]" value="80.10"></td>
</tr></tbody></table>

As per default I am dividing 320.49 / 4 to get 80.1225

By rounding 80.1225 I am getting 80.12 * 4 = 320.48‬ which is lower than 320.49

What principle shall I use to make all payments except the last one equal if the amount is not dividable to the number of payments?

Thank you for your time !

Advertisement

Answer

If you want to compute the payments in PHP, you have two options. To make the last payment the biggest, use this code:

$amount = 320.49;
$payments = array_fill(0, 3, floor($amount * 100 / 4) / 100);
$payments[3] = round($amount - $payments[0] * 3, 2);
print_r($payments);

Output:

Array
(
    [0] => 80.12
    [1] => 80.12
    [2] => 80.12
    [3] => 80.13
)

To make the last payment the smallest, use this code:

$payments = array_fill(0, 3, ceil($amount * 100 / 4) / 100);
$payments[3] = round($amount - $payments[0] * 3, 2);
print_r($payments);

Output:

Array
(
    [0] => 80.13
    [1] => 80.13
    [2] => 80.13
    [3] => 80.1
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement