Created
July 4, 2013 13:02
-
-
Save nfreear/5927529 to your computer and use it in GitHub Desktop.
Floating point Javascript: less than & greater than comparisons.
This file contains hidden or 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
/* | |
http://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison | |
*/ | |
var EPSILON = 0.000001; | |
function fp_less_than(A, B, Epsilon) { | |
Epsilon = Epsilon || EPSILON; | |
return (A - B < Epsilon) && (Math.abs(A - B) > Epsilon); | |
}; | |
function fp_greater_than(A, B, Epsilon) { | |
Epsilon = Epsilon || EPSILON; | |
return (A - B > Epsilon) && (Math.abs(A - B) > Epsilon); | |
}; | |
// TEST. | |
var A = 0.0034, | |
B = 0.0066; | |
if (fp_less_than(A, B)) { | |
document.write("A is less than B."); | |
} | |
if (fp_greater_than(A, B)) { | |
document.write("A is greater than B."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is that a typo in lesser than?
Should both tests be less than?