Skip to content

Instantly share code, notes, and snippets.

@mpriour
Created June 19, 2014 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpriour/3f617f98d374d2a6498b to your computer and use it in GitHub Desktop.
Save mpriour/3f617f98d374d2a6498b to your computer and use it in GitHub Desktop.
floating point equality in js
var eq = function(n1, n2, decimals) {
var equal = false;
if (decimals === undefined) {
decimals = 15;
}
if (decimals) {
var factor = Math.pow(10, decimals);
var a = Math.round(n1 * factor) / factor, b = Math.round(n2 * factor) / factor;
console.log(n1 + ' => ' + a + " :: " + n2 + ' => ' + b);
equal = a == b;
} else {
equal = n1 == n2;
}
return equal;
}
Number.equals=eq;
Number.prototype.equals = function(n, d){return eq(this,n,d)};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment