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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>