console.log(typeof(parseInt((0.1 + 0.2).toFixed(1)))); // number
console.log((0.1 + 0.2).toFixed(1) == 0.3); // true
console.log((parseInt((0.1 + 0.2).toFixed(1))) === 0.3); // falseRun Code Online (Sandbox Code Playgroud)
有人可以解释为什么最后一个语句不返回 true 吗?
parseInt将尝试将其参数转换为int(整数)。十进制值将变成整数。所以
(0.1+0.2).toFixed(1)
Run Code Online (Sandbox Code Playgroud)
变成0.3,并且
parseInt((0.1+0.2).toFixed(1))
Run Code Online (Sandbox Code Playgroud)
变成 0(因为parseIntfloor 非整数,而 0.3 floored 是 0)。
如果您只想转换为数字,请Number改用:
(0.1+0.2).toFixed(1)
Run Code Online (Sandbox Code Playgroud)
请记住,由于浮点数的怪异,0.1 + 0.2导致0.30000000000000004- 这就是为什么toFixed首先调用它,修剪一些小数点,需要将其与0.3正确比较。
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |