Something else I just learned today. I've been happily using parseInt
all this time, and I've been doing it wrong.
I never really thought much about it. "Ok, let's change this string to an integer. parseInt(string)
Bang. Done."
But then I got a warning when compiling my code with Google's Closure Compiler saying that I needed two parameters. Wait, what?
Turns out, there is a second parameter for the Radix that you should always fill in. This makes sense, of course, but apparently I assumed everyone used base ten. Always. That was pretty dumb, and here's why:
from the parseInt definition on MDN
- If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
- If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
- If the input string begins with any other value, the radix is 10 (decimal).
Needless to say, I'll be using both parameters from now on! (Yes, even though this is not as important since ECMAScript 5, that's still pretty new).
Comments
Post a Comment