Skip to content

Instantly share code, notes, and snippets.

@webkader
Last active August 29, 2015 14:24
Show Gist options
  • Save webkader/f1bbcd35b6674990f6d3 to your computer and use it in GitHub Desktop.
Save webkader/f1bbcd35b6674990f6d3 to your computer and use it in GitHub Desktop.
Comparing float values
// look into http://php.net/manual/en/language.types.float.php
function compareFloatValues($a, $b, $operator = '==')
{
// This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.
$epsilon = 0.00001;
// make equal to 5 digits of precision
$a = (float)$a;
$b = (float)$b;
switch ($operator) {
// must be repeated exactly
case '==':
case '===':
if (abs($a - $b) < $epsilon) {
return true;
}
break;
// must not be equal to
case "!=":
case '!==':
if (abs($a - $b) > $epsilon) {
return true;
}
break;
// must be less than
case "<":
if (abs($a - $b) < $epsilon) {
return false;
} else {
if ($a < $b) {
return true;
}
}
break;
// must be greater than
case ">":
if (abs($a - $b) < $epsilon) {
return false;
} else {
if ($a > $b) {
return true;
}
}
break;
// must be less than or equal to
case "<=":
if (compareFloatValues($a, $b, '<') || compareFloatValues($a, $b, '==')) {
return true;
}
break;
// must be greater than or equal to
case ">=":
if (compareFloatValues($a, $b, '>') || compareFloatValues($a, $b, '==')) {
return true;
}
break;
default:
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment