Hacker News new | comments | show | ask | jobs | submit login

This is not the only area in JS where it pays to be careful with numbers.

For example, the parseInt function mentioned in the article actually does magic base determination. Your string will be parsed into a base-10 number, unless it begins with '0x' in which case base-16 is used, or if it begins with a leading '0' then it is treated as base-8.

This last case has stung me on several occasions when parsing user input into numbers: User puts a leading-zero, and you magically end up with octal conversions. (I believe this whole octal thing has been deprecated in recent JS implementations).

In any case it's sensible to specify the 'radix' whenever using the parseInt function, as in parseInt(numberString, 10);

If the user deliberately puts in 0x it's probably because the number is more convenient in hex. Definitely get rid of octal though. The octal designation should have had a letter in it right from the start.

Yet another reason to use JSLint (it makes the second parameter of parseInt not optional)

you can also just use Number() to be safe

How is it different?

Think of parseInt() as what it says- parsing out the number value. Number() can be considered as a cast.

    parseInt('12', 10);  => 12
    Number('12');        => 12
    parseInt('12x', 10); => 12
    Number('12x');       => NaN

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact