ab92014
ab92014

Reputation: 13

PHP proportional division

I'm trying to write some PHP, which will divide a number and have the last result be rounded down if odd. Therefore allowing an odd number to be proportioned.

For example:

5/3 equals 1.666 recurring. The code would produce an array of 1.67, 1.67 and 1.66.

6/2 equals 2. The code would produce an array of 2, 2, 2.

I've managed to come up with this:

$total = 7;
$divide = 3;

$array = array_fill(0, $total, round($total/$divide, 2));
if($total%$divide == 1) $array[count($array)-1] = $array[count($array)-1]-0.01;

I'm wondering if there is a more logical way of doing it?

Thanks

Upvotes: 0

Views: 437

Answers (2)

Bill
Bill

Reputation: 13

Are you trying to get a collection of numbers which add up to $total? If so, I don't think your basic algorithm is correct. Consider 7/3. To two decimal places this is 2.33. Your code would produce an array of 2.33, 2.33 and 2.32, which together sum to 6.98, not 7.

Upvotes: 0

cornelb
cornelb

Reputation: 6066

I think your array should have $divide number of elements.

So 6/2 would be 3 and 3. I changed the if statement related to the remainder. I am just it to the last element.

function calculate($total, $divide) {

    $array = array_fill(0, $divide, round($total/$divide, 2));

    if($total%$divide > 0) {
        $array[count($array)-1] += $total - array_sum($array);
    }

    return $array;

}

$result = calculate(5, 3);
print_r($result);

Upvotes: 1

Related Questions