Skip to main content

Posts

Showing posts with the label numbers

Use parseInt Correctly

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: 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 ot...