Warning: Undefined array key "action" in /home/bakers/html/entryreply.php on line 5

Warning: Undefined variable $output in /home/bakers/html/entryreply.php on line 50

Warning: Undefined array key "EntrySubject" in /home/bakers/html/entryreply.php on line 51

Warning: Undefined variable $logintext in /home/bakers/html/entryreply.php on line 97

Warning: Undefined variable $reply_name in /home/bakers/html/entryreply.php on line 103

Warning: Undefined variable $reply_email in /home/bakers/html/entryreply.php on line 104
Perturb.org - interesting technology related things from around the internet

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;
}


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.233.242.204
To prevent spam please submit by clicking the kitten: