Javascript compare numbers as strings

不羁岁月 提交于 2020-06-08 20:11:07

问题


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.


回答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")
)



回答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").


来源:https://stackoverflow.com/questions/56988641/javascript-compare-numbers-as-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!