Skip to content

Instantly share code, notes, and snippets.

@nfreear
Created July 4, 2013 13:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfreear/5927529 to your computer and use it in GitHub Desktop.
Save nfreear/5927529 to your computer and use it in GitHub Desktop.
Floating point Javascript: less than & greater than comparisons.
/*
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.");
}
@cbuteau
Copy link

cbuteau commented Mar 21, 2016

Is that a typo in lesser than?
Should both tests be less than?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment