1

I simply cannot wrap my head around this:

2590.00 > 2.00 //== true  
"2590.00" > "2.00" //== true  
105.00 > 2.00 //== true  
"105.00" > "2.00" //== false???  

Why is the last expression returning false?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

4 Answers4

2
"105.00" > "2.00"

is comparing strings instead of numbers.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • I get that, but then why does "2590.00" > "2.00" //== true? – stark102088 Jul 27 '15 at 22:19
  • @stark102088 because they are string – Haozhun Jul 27 '15 at 22:19
  • Ok so...."2590.00" > "2.00" returns true and they are strings... "105.00" > "2.00" returns false and they are strings... – stark102088 Jul 27 '15 at 22:20
  • 1
    @stark102088, check string comparisons... it checks symbol by symbol, so '9' is more than '88888888888888888', cause it checks first letter and '9' > '8', thus 'true' is returned. – Ivan Jul 27 '15 at 22:22
  • 2
    As the first character in both the cases is `2`. It goes to the next char. ASCII value of `5 is 53` and `. is 46` --- So `53 > 46` which is true. – Sushanth -- Jul 27 '15 at 22:22
  • This is such a terrible answer, I don't know why @stark102088 accepted it. It does nothing more than state what he obviously already knew. –  Jul 27 '15 at 22:55
1

When comparing two strings, "2.00" will be greater than "105.00", because (alphabetically) 105.00 is less than 2.00.

When comparing a string with a numeric constant, JavaScript will treat the number as a string when doing the comparison. The result of this is commonly not the same as a numeric comparison. To secure a proper result, variables should be converted to the proper type before comparison:

Parse the string into an integer using parseInt:

javascript:alert(parseInt("105.00")>parseInt("2.00"));
ooozguuur
  • 3,396
  • 2
  • 24
  • 42
  • This answer is the only half-way decent one, but you're quoted a source without giving credit. Please update your answer so you're not plagiarizing. –  Jul 27 '15 at 22:53
0
"105.00" > "2.00"

is comparing the strings "105.00"and "2.00" and since '1' < '2' it returns false

Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
-1

I think it's because JS compare signs of string ("1" < "2" etc) instead of numbers.

xaepe
  • 71
  • 9