Floating Point Comparisons In PHP and Javascript
By Justin Laing2008-01-08
PHP Floating Point Comparison Made Easy
Here’s my php function that compares floating point numbers:
function moneycomp($a,$comp,$b,$decimals=2) {
$res = bccomp($a,$b,$decimals); // php function for comparing floating point numbers with a specified level of precision
switch ($comp) {
case ">":
return ($res==1);
case ">=":
return ($res==1 || $res==0);
case "<":
return ($res==-1);
case "<=":
return ($res==-1 || $res==0);
default:
case "==":
return ($res==0);
}
}
// example usage: if ($total > $payments) ...
if (moneycomp($total,'>',$payments)) ...
// example usage: if ($debt <= $income) ...
if (moneycomp($debt,'<=',$income) ...
// example usage: if ($cost == $price) ...
if (moneycomp($cost,'==',$price) ...
So that makes life really simple. You just write your comparisons wrapped in the moneycomp() function.
Tutorial Pages:
» Beware Comparing Floating Point Values Can Be Hazardous!
» PHP Floating Point Comparison Made Easy
» Javascript Floating Point Comparison Made Easy
» Resources And Further Reading
Originally posted on Makebeta
