投票百分比计算错误[重复]

This question already has an answer here:

I have created a php program where user can can vote on polls and after that, the poll result will displayed with only percentage, however I am facing an error in my program.
Code which I am using for percentage calculation is
<?php echo round(($num_votes / $total_votes) * 100) ?>

Now If we talk about a sample poll result, assume we have five options
option A - 4 votes
option B - 2 votes
option C - 4 votes
option D - 1 votes
option E - 0 votes
Total votes = 11

In this scenario the percentage result generating is
option A - 36%
option B - 18%
option C - 36%
option D - 9%
option E - 0%

But the total of percentage is 99% instead of 100%. What I want is total should always be 100%
Any help would be appreciated
Thanks.

</div>

If you are working with rounded numbers, you can indeed end up with...rounded numbers. And the sum of those rounded numbers will be different from the regular sum. There's little you can do to change that. If you insist, you'd have to:

  1. calculate the rounded numbers
  2. calculate the sum, and if not 100%,
  3. loop through the rounded numbers and decide which one should get the missing percent.

But you're messing with the data. You may think you're cleaning it, but you're messing it up.

There's nothing out-of-the-box you can do about it, if you floor() everything you'll miss one point, if you ceil() you'll gain one point.

You could floor() everything then if then calculate the array_sum(), if not 100 then find min() and ceil() it.

You can specify number of digits after decimal places in round. ex:round(number,2);

This way lead to ~100%, 'number_format' is nice thing

$a = 4;
$b = 2;
$c = 4;
$d = 1;
$e = 0;
$total = $a + $b + $c + $d + $e;

$arr = array(
    'a' => number_format(($a / $total) * 100, 3),
    'b' => number_format(($b / $total) * 100, 3),
    'c' => number_format(($c / $total) * 100, 3),
    'd' => number_format(($d / $total) * 100, 3),
    'e' => number_format(($e / $total) * 100, 3)
);

foreach ($arr as $answer => $percentage) {
    echo  $answer .': '. $percentage . '<br />';
}


// this will be 100.001 so we format is
echo 'total: '. number_format(array_sum($arr), 2);