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.
eval("-1")
is the slowest(by far), and the arithmetic hacks are the fastest. Wow. You could easily turn this into an interesting answer – NammuparseInt()
. – YerkovichparseInt
and 100xeval
performance. I know this may depend, but some general trends are visible I think – Nammu