Skip to content

Instantly share code, notes, and snippets.

@corymartin
Last active December 16, 2015 14:19
Show Gist options
  • Save corymartin/5447763 to your computer and use it in GitHub Desktop.
Save corymartin/5447763 to your computer and use it in GitHub Desktop.
Addition function to avoid inaccuracies of floating point addition.
var adder = function(precision) {
precision |= 0;
return function() {
var sum = 0;
var len = arguments.length;
while (len--) sum += (arguments[len] * precision) | 0;
return sum / precision;
};
};
// Example
0.1 + 0.2; //=> 0.30000000000000004
var add = adder(100);
add(0.1, 0.2); //=> 0.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment