Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

How to round up a value to get the right result in php

I want to create a simple voting program with php, but I get a problem in rounding out the results of the voting.

I have some values ​​from each of the existing topics, for example:

    $TotalVote = 13;

    $Value1 = 6;

    $Value2 = 4;

    $Value3 = 1;

    $Value4 = 1;

    $Value5 = 1;

    Echo 'Value 1:'. $Result1 = round ($value1 / $totalVote * 100);
    Echo '<br>';
    Echo 'Value 2:'. $Result2 = round ($value2 / $totalVote * 100);
    Echo '<br>';
    Echo 'Value 3:'. $Result3 = round ($value3 / $totalVote * 100);
    Echo '<br>';
    Echo 'Value 4:'. $Result4 = round ($value4 / $totalVote * 100);
    Echo '<br>';
    Echo 'Value 5:'. $Result5 = round ($value5 / $totalVote * 100);
    Echo '<br>';
    Echo 'Total Value:'. $TotalResult = $result1 + $result2 + $result3 + $result4 + $result5;`

After I add up all the rounding results, I get 101% results. I ever try to using ceil, but I get 102% resuluts.

How do I get 100% of the overall value exactly when everything is summed up?

Upvotes: 0

Views: 133

Answers (3)

Scott Machlovski
Scott Machlovski

Reputation: 270

I Edited this code defenitly work for you

<?php
 $totalVote = 13;

$value1 = 6;

$value2 = 4;

$value3 = 1;

$value4 = 1;

$value5 = 1;

Echo 'Value 1:'. $Result1 = ($value1 / $totalVote * 100);
Echo '<br>';
Echo 'Value 2:'. $Result2 = ($value2 / $totalVote * 100);
Echo '<br>';
Echo 'Value 3:'. $Result3 = ($value3 / $totalVote * 100);
Echo '<br>';
Echo 'Value 4:'. $Result4 = ($value4 / $totalVote * 100);
Echo '<br>';
Echo 'Value 5:'. $Result5 = ($value5 / $totalVote * 100);
Echo '<br>';
Echo 'Total Value:'. $totalVote = $Result1 + $Result2 + $Result3 + $Result4 + $Result5;
?>

Upvotes: 0

UfguFugullu
UfguFugullu

Reputation: 2147

You can try this code

$values = [6,4,1,1,1];
$total_vote = array_sum($values);
$total_result = 0;

foreach ($values as $index => $value) {
    $result = $value / $total_vote * 100;
    $total_result += $result;
    echo 'Value ' . ($index + 1) . ': ' . round($result) . '<br/>';
}

echo 'Total Value: ' . round($total_result);

And this code will produce the following output

Value 1: 46
Value 2: 31
Value 3: 8
Value 4: 8
Value 5: 8
Total Value: 100

Upvotes: 1

Arjen
Arjen

Reputation: 396

That is what you get for rounding. Your logic makes no sense. Calling something the total value does not make it the total value, it's just the sum of the rounded values :-)

3 voters with values unique values gives 33% rounded for each group. That makes 99% total. Ceil() would give 34*3 = 102.

Upvotes: 1

Related Questions