Javascript >= 与两个负数比较产生不正确的结果

Javascript >= comparison with two negative numbers producing incorrect result

我遇到过奇怪的行为,在使用 toFixed() 之前和之后,相同的数字明显大于另一个(正确)。但是 toFixed() 版本产生了不正确的比较?当两个数字都是负数并且 >= 是操作数时,这似乎会发生。

let lastVal = 0.091;
let currentVal = 0.093;
let newVal = 0.094;

let oldSlope = lastVal - currentVal;
let newSlope = currentVal - newVal;
let oldSlopeFixed = (lastVal - currentVal).toFixed(16);
let newSlopeFixed = (currentVal - newVal).toFixed(16);

document.getElementById("one").innerHTML = "oldSlope = " + oldSlope + ", newSlope = " + newSlope;
document.getElementById("two").innerHTML = "oldSlopeFixed = " + oldSlopeFixed + ", newSlopeFixed = " + newSlopeFixed;

if ((newSlope) >= (oldSlope))
{
    document.getElementById("three").innerHTML = "newSlope >= oldSlope  (correct)";
}
if (!((newSlopeFixed) >= (oldSlopeFixed)))
{
    document.getElementById("four").innerHTML = "newSlopeFixed < oldSlopeFixed  (incorrect ... what???)";
}
<!DOCTYPE html>
<html>
<body>

<p id="one"></p>
<p id="two"></p>
<p id="three"></p>
<p id="four"></p>

</body>
</html>

toFixed 产生一个字符串。您不是在比较数字,而是在比较按字母顺序比较的字符串。

console.log(-0.001 <= -0.002)     // false
console.log('-0.001' <= '-0.002') // true

在计算之前不要使用toFixed。当所有计算都已完成并且您正在尝试格式化数字以供人类使用时使用它。