// 解释一下下面代码的输出
console.log(0.1 + 0.2); //0.30000000000000004
console.log(0.1 + 0.2 == 0.3); //false
// 对于保证浮点数计算的正确性,有两种常见方式。
// 一是先升幂再降幂:
复制代码
1
2
3
4
5
6
7
8
9
10function add(num1, num2){ let r1, r2, m; r1 = (''+num1).split('.')[1].length; r2 = (''+num2).split('.')[1].length; m = Math.pow(10,Math.max(r1,r2)); return (num1 * m + num2 * m) / m; } console.log(add(0.1,0.2)); //0.3 console.log(add(0.15,0.2256)); //0.3756
转载于:https://www.cnblogs.com/laneyfu/p/7065906.html
最后
以上就是腼腆八宝粥最近收集整理的关于对于保证浮点数计算的正确性,有两种常见方式的全部内容,更多相关对于保证浮点数计算内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复