Get Percentage Of A Number With PHP

Wednesday, June 4, 2008 - 09:47

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.

1
2
3
4
5
6
7
8
function get_percentage($total, $number)
{
  if ( $total > 0 ) {
   return round($number / ($total / 100),2);
  } else {
    return 0;
  }
}

Here are some examples of the function in action.

1
2
3
4
5
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%
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

That percentage script saved my arse. You rule.

hi . i'm from iran
I was a long time in search for the this formula
thanks for this formula , administrator :)

Add new comment