qweqweqwe
qweqweqwe

Reputation: 343

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?

Upvotes: 3

Views: 15241

Answers (5)

Fallen
Fallen

Reputation: 4565

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.

Upvotes: 7

FbInfo
FbInfo

Reputation: 103

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

=)

Upvotes: 0

rjmunro
rjmunro

Reputation: 28056

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.

Upvotes: 7

srakl
srakl

Reputation: 2619

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

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

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

Or you can use

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

Or

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

Upvotes: 1

Related Questions