Javascript weirdness with toFixed

Comparison of floats. According to the cam block, code 5 is greater than 37.66. The second block claims that 5 is less than 37.66. What is toFixed () to make the first block respond as it does? (This was only 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

+4
source share
2 answers

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

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 are trying to accomplish. How about this:

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

edit: semicolons added

+6
source

The first is incorrect, since .toFixed will return a string, and a string that is larger than the other does not make sense in this context

0
source

All Articles