Search code examples
javascripttype-conversion

Best way to parse an int in Javascript


One can convert a string to an integer in numerous ways, e.g.

  • parseInt("-1",10)
  • Math.floor("-1")
  • Number("-1")
  • "-1"|0
  • ~~"-1"

I assume the first is the canonical form, but e.g. uses the third one to coerce ints. There are probably more ways to do it.

What are the differences and benefits of using each of these? Which is expected to be the fastest?


Solution

  • The canonical way to parse a decimal int is parseInt(str, 10).

    Regarding other solutions :

    • parseInt("-1") : use it only if you like to live dangerously (some browsers assume "009" is decimal, not all)
    • Math.floor("-1") : it might be a floor and not an int, but that's not the right way if you want to be sure it's an integer
    • Number("-1") : maybe you want an object so you can call methods without promotion and you want to be sure there's no garbage (Number('3 flowers') ==> NaN)
    • "-1"|0, ~~"-1" and other combinations of implicit conversion and binary operation : you like code golf and don't want your code to be easily maintained (for those wondering : a binary operation takes the integer part of a number). As noted by Blender in comment, those solutions aren't suitable for big (positive or negative) numbers.

    You should not use another solution than parseInt(str,10) if you don't need to ensure the string contains nothing else than an int. That's the fastest solution and, more importantly, the most readable. If a JS engine does some optimizations, there is no reason for other solutions to get faster than this one.