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? Commented Nov 19, 2014 at 15:05
  • You could do something funny with Function constructor Commented Nov 19, 2014 at 15:08
  • @aduch You can always do something funny with the function constructor ;). But I prefer not to evaluate stuff Commented 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. Commented 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.

Sign up to request clarification or add additional context in comments.

1 Comment

So it's because '4'.charCodeAt() < '5'.charCodeAt()?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.