Calculate a percentage

Below is a quick function that simplifies the process of calculating a percentage in PHP.

<?php
function percent($Amount = 0, $Total = 0, $Decimal = 0) {
	// Make sure our numbers are actually numbers
	$Amount = (INT) $Amount;
	$Total = (INT) $Total;
	$Decimal = (INT) $Decimal;
	// Cannot divide by zero so check if Total = 0
	if ($Total === 0) {
		return 0;
	}
	$p = $Amount / $Total;
	// Multiply by 100 to move decimal point to correct location
	$p *= 100;
	// Return the percentage with specified decimal places
	return number_format($p, $Decimal);
}
?>

Then to use this code you can do:

<?php
// prints out 10% on the screen
echo percent(10, 100),'%';
?>
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • BlinkList
  • FriendFeed
  • LinkedIn
  • MySpace
  • Slashdot
  • StumbleUpon
  • Twitter
  • Yahoo! Bookmarks
  • Add to favorites
  • email

2 Responses to “Calculate a percentage”

  1. GMoney Says:

    This is a bit shorter:


  2. GMoney Says:

    whoops..

    function percent($amount,$total,$decimal=0){
    if(0===(int)$total){
    return $total;
    }
    return number_format((((int)$amount/(int)$total)*100),$decimal);
    }


Switch to our mobile site