Round Percentages PHP
Solution 1
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.
Solution 2
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.
Solution 3
echo intval(($fakecount / $totalcount) * 100);
Or you can use
echo floor(($fakecount / $totalcount) * 100); //Round down
Or
echo ceil(($fakecount / $totalcount) * 100); // Round Up
Related videos on Youtube
qweqweqwe
Updated on June 21, 2022Comments
-
qweqweqwe almost 2 years
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?
-
Samuel Cook almost 11 yearsadd the
* 100
inside of the round:echo round($fakecount / $totalcount * 100);
-
-
rjmunro almost 11 years
intval()
is the same asfloor()
. Useround()
-
rjmunro almost 11 yearsCasting to
int
is the same asfloor()
. Useround()
to get the nearest value. -
Fallen almost 11 years@rjmunro my one will return the same value as round() as I added 0.5 before type casting :)
-
rjmunro almost 11 yearsSorry, didn't spot that. Are you sure that the performace of casting to int is better than using round() by enough of a margin to be faster than the extra addition?
-
Fallen almost 11 years@rjmunro: I'm not sure about the runtime performance. but not all languages have round() function, but casting to int after adding 0.5 is a good way to do in all languages. and if it's about runtime I think the difference would be negligible as round function has to do something similar (I don't know exactly how
round()
rounds a number)