Round Percentages PHP

qweqweqwe picture qweqweqwe · Jul 15, 2013 · Viewed 10.2k times · Source

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?

Answer

rjmunro picture rjmunro · Jul 15, 2013

You need to multiply by 100 before you round, not after:

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

You are calculating $fakecount / $totalcount, which will be a number between 0 and 1, then you round that, so you get either 0 or 1, then you multiply by 100, giving either 0 or 100 for your percentage.