Search code examples
phpsqlrounding-error

PHP rounding issue


I am getting a rounding issues, I have a database of 3 charities with different amounts.. then in the front I have the 3 charities displaying there percentage based on the amount assigned to them and the total percentage always needs to add to 100%.. currently if each charity has 1 assigned to it, it displays 33% on each which equals 99% where i need to cheat it in a way to always be equal to 100%..

Here is the PHP

$charity = $_POST['charity'];
$sql = "SELECT amount FROM charities";
$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)) {
    $total += $row['amount'];
}

$sql_individual = "SELECT * FROM charities WHERE charity='$charity'";
$result_individual = mysqli_query($con, $sql_individual);

while($row = mysqli_fetch_array($result_individual)) {
    $charity = $row['amount'];
}

echo round($charity / $total * 100,0) . "%";

I found a maths solution for this.. but.. my maths isn't all that great.. but.. okay in all honesty i do not understand this fully:

c = 100 - (a + b) - e,g 34 = 100 - (33 + 33) 

any Help Greatly Appreciated..


Solution

  • There are no rounding issues, You just round to an integer numbers, that means that if You have 5 values like these:

    1. 12,25%
    2. 13,25%
    3. 20,25%
    4. 30,25%
    5. 34,00%

    after using round($x, 0) on them they will be rounded to these values:

    1. 12
    2. 13
    3. 20
    4. 30
    5. 34

    After summing these rounded values You get the value of 99.

    It is best to round at least to two decimal places when working with percentages - and only for displaying purposes. You shouldn't round any values that will be used for further math operation...