Johan
Johan

Reputation: 35223

Comparing numbers of type string

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?

Upvotes: 0

Views: 83

Answers (1)

rosscj2533
rosscj2533

Reputation: 9323

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.

Upvotes: 1

Related Questions