console.log(0.1+0.2 == 0.3) true 还是false js中为什么0.1+0.2 不等于 0.3 解决方案

147 阅读1分钟

在常规的一些面试题目中 可能会出现这样一道笔试题 console.log(0.1+0.2 == 0.3) true 还是false 通过打印我们会发现真实的结果是大于 0.3 的 why?

原因:JS中采用的IEEE 754的(64位)双精度标准,计算机内部存储编码时,0.1在计算机内部不是精确的0.1,是一个误差值 故 0,1+0.2 > 0.3,

解决办法 1 toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。 console.log((0.1 + 0.2).toFixed(10)) //0.3000000000

console.log((0.1 + 0.2).toFixed(10) == 0.3);//true 
console.log(Number((0.1 + 0.2).toFixed(10)) === 0.3); //全等
console.log(Number(0.1 + 0.2) == 0.3); //false

2 先分别乘 10 再除以10 其实也就是先转化为了正整数

console.log((0.1 * 10 + 0.2 * 10) / 10 === 0.3); //true

3.引入math.js 或者bigNumber.js 解决 说一下 math.js
1.安装 使用 npm install mathjs 2.引入使用 <script src="https://unpkg.com/mathjs@7.0.1/dist/math.min.js" type="text/javascript"></script>

const ans = math.add(0.1, 0.2)     //  0.30000000000000004
console.log(math.format(0.1 + 0.2, { precision: 10 })) // '0.3'

precision 这个用来设置精确度 
console.log(math.format(0.1 + 0.2, { precision: 18 })) //0.30000000000000004