我遇到了奇怪的行為,在使用 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>
uj5u.com熱心網友回復:
toFixed產生一個字串。您不是在比較數字,而是在比較按字母順序比較的字串。
console.log(-0.001 <= -0.002) // false
console.log('-0.001' <= '-0.002') // true
請勿toFixed 在計算前使用。當所有計算完成并且您嘗試格式化數字以供人類消費時使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477956.html
標籤:javascript 操作数 固定的
