Defaulting the radix to 8 (if the string starts with a 0) in JavaScript's parseInt function annoys me, only because I continue to forgot to pass the optional second argument as 10. I'm looking for an answer telling me why it makes sense to have it default to 8.
By default radix is 10 (decimal).
Differences. Number() converts the type whereas parseInt parses the value of input. As you see, parseInt will parse up to the first non-digit character. On the other hand, Number will try to convert the entire string.
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
It only "defaults" to 8 if the input string starts with 0. This is an unfortunate carryover from C and C++.
You can use Number('0123')
instead, or, as you said in the question, parseInt('0123', 10)
.
How do I work around JavaScript's parseInt octal behavior?
Can you tell me more about this carryover?
Note: ECMAScript strict mode removes octal syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With