Calculate a percentage
Jun 4, 2010 PHP Coding
Below is a quick function that simplifies the process of calculating a percentage in 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:
// prints out 10% on the screen echo percent(10, 100),'%';
