Get Percentage Of A Number With PHP

Use the following function to find the percentage value of one number to another. If the $total parameter is zero then zero is returned as this would otherwise result in a division by zero error.

function get_percentage($total, $number)
{
  if ( $total > 0 ) {
   return round(($number * 100) / $total, 2);
  } else {
    return 0;
  }
}

Here are some examples of the function in action.

echo get_percentage(100,50).'%'; // 50%
echo get_percentage(100,10).'%'; // 10%
echo get_percentage(100,100).'%'; // 100%
echo get_percentage(400,3).'%'; // 0.75%
echo get_percentage(1234,4321).'%'; // 350.16%

Comments

That percentage script saved my arse. You rule.
Permalink
hi . i'm from iran I was a long time in search for the this formula thanks for this formula , administrator :)
Permalink
thanks for share..
Permalink
Thanks
Permalink

I just had to swap $total and 100 over for my purposes, i.e returning 100/200 as 50%.

Permalink

Hello Philip, that formula does not generate the correct %, then I write the correct one: (number * 100) / total:

/*

return round(($number * 100) / $total, 2);

*/

Permalink

Quite right. It must have been right at some point but it's clearly been wrong for a while.

Thanks for the correction! I've updated the code.

Name
Philip Norton
Permalink

Really liked this post, thanks!

Permalink

Hi, 

Lovely Script.

But I am looking for one that takes a value, EG Dollars, and multiples it by 11% and gives an answer. Any help?

Thanks in advance.

Permalink

You mean something like this?

function multiply_by_percentage($number, $percent) {
  return $number * ($number * $percent / 100);
}

 

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
11 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.