Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".localeCompare("3085")
-1

Output in second and third case is not as expected.

I know it sorts in Lexicographical order but still I am having trouble understanding why is it so and how should I overcome this.

Any help would be appreciated.

like image 209
user3807691 Avatar asked Feb 17 '26 04:02

user3807691


2 Answers

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")
)
like image 179
adiga Avatar answered Feb 18 '26 17:02

adiga


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").
like image 30
AKX Avatar answered Feb 18 '26 18:02

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!