Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

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

Or you can use

echo floor(($fakecount / $totalcount) * 100);  //Round down

Or

echo ceil(($fakecount / $totalcount) * 100);  // Round Up

use the round() function

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

http://php.net/manual/en/function.round.php

others you can use are

  • ceil() - Round fractions up
  • floor() - Round fractions down

Nope...

There is a lot of ways to do it.

$mypercent = ($fakecount / $totalcount) * 100;

Remember.. this will first run what is inside of (xxx) and after will * 100.

After this...

echo round($mypercent);

And you can use a lot of rules on that too if you want...

<i>if ($value < 10) {
    $value = floor($value);
} else {
    $value = round($value);
}</i>

Dont forget to see that other to commands too, maybe you are going to need it.

ceil() - Round fractions up

floor() - Round fractions down

=)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top