0

I'm wanting to convert some numbers into a percentage of each other. The following code works some times but every so often it'll be off by a decimal place.

The problem is with the round(); function. From the example below you will see the percentage values add up to 100.01. This breaks my pie chart. :(

How may I fix this? So the corresponding percentage values will always hit 100 when added together.

$total['one']['value'] = '158';
$total['two']['value'] = '129';
$total['three']['value'] = '121';

$total['all'] = $total['one']['value'] + $total['two']['value'] + $total['three']['value'];

$total['one']['percent'] = round(($total['one']['value'] / $total['all']) * 100, 2);
$total['two']['percent'] = round(($total['two']['value'] / $total['all']) * 100, 2);
$total['three']['percent'] = round(($total['three']['value'] / $total['all']) * 100, 2);

Returns:

Array
(
    [one] => Array
        (
            [value] => 158
            [percent] => 38.73
        )

    [two] => Array
        (
            [value] => 129
            [percent] => 31.62
        )

    [three] => Array
        (
            [value] => 121
            [percent] => 29.66
        )

    [all] => 408
)
ditto
  • 5,917
  • 10
  • 51
  • 88

1 Answers1

1
$total['three']['percent'] = 100-($total['one']['percent']+$total['two']['percent']);
if($total['three']['percent'] < 0 && $total['two']['percent'] > 0-$total['three']['percent']){
    $total['two']['percent'] += $total['three']['percent'];
    $total['three']['percent'] = 0;
}else if($total['three']['percent'] < 0){
    $total['one']['percent'] += $total['three']['percent'];
    $total['three']['percent'] = 0;
}

Demo with $total from OP: http://codepad.org/ydzpbHZr
Additional demos with different values for precent: http://codepad.org/A9aUgniA and http://codepad.org/1bDaH4TX.

Mooseman
  • 18,763
  • 14
  • 70
  • 93