无意间看到这篇博主的文章,里面解析了JS小数精度丢失的根本原因juejin.cn/post/727054…
我想到一个法子,既然是截取造成的精度丢失,能不能在运算时给它补回来
先前:
console.log((1.05).toFixed(1)); // 1.1 正确
console.log((1.005).toFixed(2)); // 1.00 错误
console.log((1.0005).toFixed(3)); // 1.000 错误
console.log((1.00005).toFixed(4)); // 1.0001 正确
console.log((1.000005).toFixed(5)); // 1.00001 正确
console.log((1.0000005).toFixed(6)); // 1.00001 正确
console.log((1.00000005).toFixed(7)); // 1.000000 错误
console.log((1.000000005).toFixed(8)); // 1.0000000 错误
加上最小数值后再 toFixed()
console.log((1.05 + Number.EPSILON).toFixed(1)); // 1.1 正确
console.log((1.005 + Number.EPSILON).toFixed(2)); // 1.01 正确
console.log((1.0005 + Number.EPSILON).toFixed(3)); // 1.001 正确
console.log((1.00005 + Number.EPSILON).toFixed(4)); // 1.0001 正确
console.log((1.000005 + Number.EPSILON).toFixed(5)); // 1.00001 正确
console.log((1.0000005 + Number.EPSILON).toFixed(6)); // 1.00001 正确
console.log((1.00000005 + Number.EPSILON).toFixed(7)); // 1.000001 正确
console.log((1.000000005 + Number.EPSILON).toFixed(8)); // 1.0000001 正确
不知道再其他情况下还能不能正常使用,感觉很不稳妥哈哈哈哈
发出来就是挨骂的,多挨骂才能成长 [dog]