Last active
August 29, 2015 14:24
-
-
Save webkader/f1bbcd35b6674990f6d3 to your computer and use it in GitHub Desktop.
Comparing float values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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