为什么 parseInt 向 toFixed 返回不同的结果?

Apu*_*ria 1 javascript

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); // false
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么最后一个语句不返回 true 吗?

Cer*_*nce 7

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导致0.30000000000000004- 这就是为什么toFixed首先调用它,修剪一些小数点,需要将其与0.3正确比较。