0

I'm implementing a sort function and came across the following:

'49' > '5' // false
'49' > '4' // true

new String(49).localeCompare('4') // 1
new String(49).localeCompare('5') // -1

Expected behaviour is obviously that 49 > 4 or 5 should be true. Is there any way to solve this without converting the strings to numbers?

4
  • Are you asking this out of curiosity or did you face any issue converting to numbers, as in a performance hit?
    – Aravind
    Nov 19, 2014 at 15:05
  • You could do something funny with Function constructor
    – axelduch
    Nov 19, 2014 at 15:08
  • @aduch You can always do something funny with the function constructor ;). But I prefer not to evaluate stuff
    – Johan
    Nov 19, 2014 at 15:09
  • 1
    @Johan: String comparison can be altered by wrapping the string into objects and defining your valueOf operators. Way too much work, but nevertheless possible. Just telling, probably you know it, using a + in front of the string converts it to a number.
    – Aravind
    Nov 19, 2014 at 15:12

1 Answer 1

1

That is actually expected behavior when comparing strings, as described here. The easiest thing for this situation would be to convert the values to numbers for comparison if you want to compare them as numbers.

Thinking outside the box a little, you could first compare the length of the strings before using the > operator. If they are numeric strings, the longer string would have a higher value (assuming you don't have numbers like '0024'). If they are equal in length, the > operator would then work as you expect.

1
  • So it's because '4'.charCodeAt() < '5'.charCodeAt()?
    – Johan
    Nov 19, 2014 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.