Search code examples
phpvariablesmathechodivide

Round Percentages PHP


I'm currently dividing two values in order to get the percentage from the actual count and the total count for my application.

I am using the following formula:

echo ($fakecount / $totalcount) * 100;

That is giving me a value like: 79.2312313. I would perefer a value like 79%.

I have tried the following:

echo round($fakecount / $totalcount) * 100; 

this doesn't seem to work correctly.

Any suggestions?


Solution

  • try,

    echo (int)($fakecount * 100 / $totalcount + .5);
    

    This works because adding 0.5 increases the integer part by 1 if the decimal part is >= .5

    or,

    round ($fakecount * 100 / $totalcount); 
    

    Note that, I'm doing the multiplication by 100 before the division to better preserve the precision.