简体   繁体   English

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

[英]Javascript >= comparison with two negative numbers producing incorrect result

I've come across strange behaviour where both before and after using toFixed() the same number is visibly greater than the other (correct).我遇到了奇怪的行为,在使用 toFixed() 之前和之后,相同的数字明显大于另一个(正确)。 However the toFixed() version produces an incorrect comparison?但是 toFixed() 版本会产生不正确的比较? This seems to happen when both numbers are negative and >= is the operand.当两个数字都是负数并且 >= 是操作数时,这似乎会发生。

 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 produces a string. toFixed产生一个字符串。 You aren't comparing numbers, you're comparing strings, which are compared alphabetically.您不是在比较数字,而是在比较按字母顺序比较的字符串。

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

Don't use toFixed before calculations.不要在计算使用toFixed It is used when all calculations are done and you're trying to format a number for human consumption.当所有计算完成并且您尝试格式化数字以供人类使用时使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM