开发者

javascript weirdness with toFixed

Comparing floats. According to the fist block of code, 5 is greater than 37.66. The second block claims that 5 is less than 37.66. What is toFixed() doing to these that makes the first block react the way it does? (This has only been tested on chrome in ubuntu)

amount = 5
total = 37.66
check = null
if(parseFloat(amount).toFixed(2) >= parseFloat(total).toF开发者_如何学编程ixed(2)){
    check = "amount IS GREATER"
}

check >> "amount IS GREATER"

amount = 5
total = 37.66
check = null
if(parseFloat(amount.toFixed(2)) >= parseFloat(total.toFixed(2))){
    check = "amount IS GREATER"
}

check >> null


number.toFixed() returns a string, so your comparison is not a numeric comparison.

This should work:

amount = 5;
total = 37.66;
check = null;
if(parseFloat(amount.toFixed(2)) >= parseFloat(total.toFixed(2))){
    check = "amount IS GREATER";
}

However, this is a somewhat strange way to accomplish what you're trying to accomplish. How about this instead:

amount = 5;
total = 37.66;
check = null;
if( Math.round(amount * 100) > Math.round(total * 100)) {
    check = "amount IS GREATER";
}

edit: added semicolons


The first one is not correct since .toFixed will return a string, and a string being greater than the other doesn't make sense in this context

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜