Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

【Q568】为何 0.1+0.2 不等于 0.3,应如何做相等比较

Open shfshanyue opened this issue 3 years ago • 4 comments

shfshanyue avatar Jun 02 '21 02:06 shfshanyue

0.1,0.2 表示为二进制会有精度的损失,比较时可引入一个很小的数值 Number.EPSILON 容忍误差,其值为 2^-52。

function equal (a, b) {
  return Math.abs(a - b) < Number.EPSILON
}

shfshanyue avatar Jun 02 '21 02:06 shfshanyue

https://zhuanlan.zhihu.com/p/87672024

illumi520 avatar Oct 27 '21 10:10 illumi520

十进制转二进制计算后再转十进制输出导致的误差

illumi520 avatar Oct 27 '21 10:10 illumi520

function add(n1 , n2){
    // ...省略参数类型判断及容错代码
    const nums1Digits = n1.toString().split('.')[1].length
    const nums2Digits = n2.toString().split('.')[1].length
    const baseNum = Math.pow(10, Math.max(nums1Digits , nums2Digits))
    // 或者用10 ** Math.max(nums1Digits , nums2Digits)
    return (n1 * baseNum + n2 * baseNum) / baseNum
}

console.log(0.1 + 0.2) // 0.30000000000000004
console.log(add(0.1, 0.2)) // 0.3

wuzqZZZ avatar Aug 28 '22 12:08 wuzqZZZ