0.1 + 0.2 // 0.30000000000000004
sumFloats([0.1, 0.2]) // 0.3
Last active
August 29, 2015 13:57
-
-
Save NV/9613722 to your computer and use it in GitHub Desktop.
Precise sum of float numbers.
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
function sumFloats(floats) { | |
var power = floats.reduce(function(acc, current) { | |
var power = getPrecision(current.toString()); | |
return Math.max(power, acc); | |
}, 0); | |
var sum = floats.reduce(function(prev, current) { | |
return prev + current; | |
}, 0); | |
var precision = Math.pow(10, power); | |
return Math.round(sum * precision) / precision; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment