Last active
January 4, 2018 14:45
-
-
Save xialvjun/16ff540733081b1f76d65d1bba3b34c0 to your computer and use it in GitHub Desktop.
javascript safe add two float without worrying about float precision
This file contains hidden or 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
// 其实这并不 safe。。。因为 js 中所有的数字其实都是浮点数,哪怕整数也是浮点数。。。 | |
// 数值比较小的整数可能看不出来浮点数的特性,但是当数值比较大时,就能看出来了 | |
// 还是直接用库来的方便实在:https://github.com/defunctzombie/num | |
function safe_add(a, b) { | |
const decimal_length = Math.max(...[a, b].map(n => (n + '').split('.')).map(n => (n[1] || '').length)); | |
const power = Math.pow(10, decimal_length); | |
// 不要把 a*power+b*power 变为 (a+b)*power | |
return Math.round(a * power + b * power) / power; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment