Get Percentage Of A Number With PHP

4th June 2008 - 1 minute read time

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. function get_percentage($total, $number)
  2. {
  3. if ( $total > 0 ) {
  4. return round($number * ($total / 100),2);
  5. } else {
  6. return 0;
  7. }
  8. }

Here are some examples of the function in action.

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

Comments

Permalink
That percentage script saved my arse. You rule.

Ben Althauser (Mon, 04/13/2009 - 23:18)

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

Amir (Sun, 10/16/2016 - 01:13)

Permalink
thanks for share..

vipjatt (Thu, 06/01/2017 - 03:19)

Permalink
Thanks

kvanacht (Tue, 01/23/2018 - 05:49)

Permalink

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

Tim (Wed, 03/03/2021 - 15:23)

Add new comment

The content of this field is kept private and will not be shown publicly.