Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function to divide money (numbers with 2 decimal points) as evenly as possible between any given number of recipients
<?php
echo nl2br(print_r(divide_money_evenly((float)(string) 78.23, 3), true));
function divide_money_evenly($number, $divided_by, $numbers=array()) {
$total = 0;
for($i=1; $i<=$divided_by; $i++) {
if(abs($number - $total) != 0) {
$divided = $number / $divided_by;
if($divided < 1) {
$rounded = 0;
}
else {
$rounded = floor($divided);
}
if($rounded == 0) {
$total += 0.01;
if(isset($numbers[$i])) {
$numbers[$i] = $numbers[$i] + 0.01;
}
else {
$numbers[$i] = 0.01;
}
}
else {
$total += $rounded;
if(isset($numbers[$i])) {
$numbers[$i] = $numbers[$i] + $rounded;
}
else {
$numbers[$i] = $rounded;
}
}
}
}
$difference = $number - $total;
if($difference > 0) {
$numbers = divide_money_evenly(float)(string) $difference, $divided_by, $numbers);
}
return $numbers;
}
@benjaminprojas

This comment has been minimized.

Copy link
Owner Author

benjaminprojas commented Nov 29, 2012

This should echo out an array like this:

Array
(
[1] => 26.08
[2] => 26.08
[3] => 26.07
)

@sudokode

This comment has been minimized.

Copy link

sudokode commented Jun 27, 2017

Cool, thanks! Figured I'd post a smaller version since this got me started:

<?php

$total = 78.23;
$divisor = 3;

$total = (float) round($total, 2);

$splitTotals = array_fill(1, $divisor, round($total / $divisor, 2));

$newTotal = $splitTotals[1] * $divisor;

$difference = abs(round($newTotal - $total, 2));

$index = $divisor;
while ($difference > 0) {
    $index = $index > 0 ? $index : $divisor;

    $difference -= 0.01;

    $splitTotals[$index--] += $newTotal < $total ? 0.01 : -0.01;
}

print_r($splitTotals);

Should give the same result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.