PHP: Calculate the percentage difference between two numbers
I need to compare two numbers and see if they're close to each other. Specifically I wanted to see if two numbers were within 3% of of each other. I wrote this simple function to calculate the percentage difference between two numbers, and optionally (with the third parameter) return true
or false
if they're within a given range. This should allow me to do a "fuzzy compare" on two numbers.
function percent_diff($a, $b, $ok_per = null) {
$per_diff = abs((1 - ($a / $b)) * 100);
if (is_numeric($ok_per)) {
$ok = $per_diff < $ok_per;
return $ok;
}
return $per_diff;
}