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),'%';
?>

Switch to our mobile site