Skip to content

Instantly share code, notes, and snippets.

@xialvjun
Last active January 4, 2018 14:45
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 xialvjun/16ff540733081b1f76d65d1bba3b34c0 to your computer and use it in GitHub Desktop.
Save xialvjun/16ff540733081b1f76d65d1bba3b34c0 to your computer and use it in GitHub Desktop.
javascript safe add two float without worrying about float precision
// 其实这并不 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