Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding in PHP to achieve 100%

Tags:

php

I need to total the number of clicks over 10 links on my page and then figure out the percentage of people that clicked each. This is easy division, but how do I make sure that I get a round 100% at the end.

I want to use the below code, but am worried that a situation could arise where the percentages do not tally to 100% as this function simply removes the numbers after the period.

function percent($num_amount, $num_total) {
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = number_format($count2, 0);
echo $count;
}

Any advice would be much appreciated.

like image 230
Somk Avatar asked Feb 19 '23 01:02

Somk


1 Answers

Instead of calculating one percentage in your function you could pass all your results as an array and process it as a whole. After calculating all the percentages and rounding them make a check to see if they total 100. If not, then adjust the largest value to force them all to total 100. Adjusting the largest value will make sure your results are skewed as little as possible.

The array in my example would total 100.02 before making the adjustment.

function percent(array $numbers)
{
    $result = array();
    $total = array_sum($numbers);

    foreach($numbers as $key => $number){
        $result[$key] = round(($number/$total) * 100, 2);
    }

    $sum = array_sum($result);//This is 100.02 with my example array.

    if(100 !== $sum){
        $maxKeys = array_keys($result, max($result));
        $result[$maxKeys[0]] = 100 - ($sum - max($result));
    }
    return $result;
}


$numbers = array(10.2, 22.36, 50.10, 27.9, 95.67, 3.71, 9.733, 4.6, 33.33, 33.33);
$percentages = percent($numbers);
var_dump($percentages);
var_dump(array_sum($percentages));

Output:-

array (size=10)
  0 => float 3.51
  1 => float 7.69
  2 => float 17.22
  3 => float 9.59
  4 => float 32.86
  5 => float 1.28
  6 => float 3.35
  7 => float 1.58
  8 => float 11.46
  9 => float 11.46
float 100

This will also work with an associative array as the function parameter. The keys will be preserved.

These figures could now be presented in a table, graph or chart and will always give you a total of 100%;

like image 63
vascowhite Avatar answered Feb 27 '23 18:02

vascowhite