Javascript Compare Numbers As Strings
I wish to compare two strings in javascript. I am using localeCompare method but the output is not as expected 116457 < 3085 false '116457' < '3085' true '116457'.localeCo
Solution 1:
If you want to compare them without converting them to numbers, you can set numeric: true
in the options
parameter
console.log(
"116457".localeCompare("3085", undefined, { numeric: true })
)
console.log(
"116457".localeCompare("3085")
)
Solution 2:
If 116457 were a word, it would come before 3085 in a dictionary.
Consider a dictionary with
- "applicative" (a long word starting with "a", c.f. a long digit string starting with "1")
- "copy" (a short word starting with "c", c.f. a shorter digit string starting with "3").
Post a Comment for "Javascript Compare Numbers As Strings"