Created
June 19, 2014 15:36
-
-
Save mpriour/3f617f98d374d2a6498b to your computer and use it in GitHub Desktop.
floating point equality in js
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
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