Reputation: 4732
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).toFixed(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
Upvotes: 4
Views: 1469
Reputation: 7334
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
Upvotes: 6
Reputation: 8805
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
Upvotes: 0