-2

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 !

Europeuser
  • 934
  • 1
  • 9
  • 32

2 Answers2

1

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

Nick
  • 138,499
  • 22
  • 57
  • 95
0

You can use this to get the remaining amount, and avoid the problem for PHP Floating point precision:

$tot = 320.49;
$qty = 4;
echo $singlePayment = number_format(($tot / $qty), 2, '.', '')+0;
echo '<br>';
echo $exceed = number_format(($tot / $qty) - number_format(($tot / $qty), 2, '.', ''), 10, '.', '')*$qty+0;
if($exceed > 0)
{
    // add this to the last payment
}

output:

80.12
0.01
user2342558
  • 5,567
  • 5
  • 33
  • 54