数字中 .
的问题
先看代码
var a = 3.1415;
a.toFixed(); // "3"
a.toFixed(1); // "3.1"
a.toFixed(2); // "3.14"
a.toFixed(3); // "3.142"
a.toFixed(4); // "3.1415"
a.toFixed(5); // "3.14150"

注意第四条四舍五入,最后一条的末位补0
上面运算中的 .
运算符需要注意一下,它是一个有效的数字字符,会被优先识别为数字常亮的一部分,然后才是对象属性访问运算符。
错误用法运用:
其中3.toFixed()
调用是无效的, .
被当做3.
中的一部分,所以无法调用toFiexed()
方法

若想实现正确调用,需如下方式调用
- 没有小数点的需要在数字前后补
.
- 用小括号将数字扩起来

较小的数值
二进制浮点中一个最大的问题
0.1 + 0.2 === 0.3; // false
按着正常思路,判断结果应该是true
,但是结果却是false
,出现这种情况的原因是 二进制浮点数中的 0.1 和 0.2 并不是十分精确,他们相加的结果并不是0.3,而是一个比较接近的数字 0.30000000000000004

解决方法:Number.EPSILON

在ES6
中可以尝试使用Number.EPSILON

网友评论