News for hackers. Stuff that matters.
Re:Be careful with JS numbers by jamestnz on Sunday January 13, 2013 @02:43PM (#5051617)
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);

Re:Be careful with JS numbers by Dylan16807 on Sunday January 13, 2013 @02:53PM (#5051660)
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.
Re:Be careful with JS numbers by frewsxcv on Sunday January 13, 2013 @03:00PM (#5051694)
Yet another reason to use JSLint (it makes the second parameter of parseInt not optional)
Re:Be careful with JS numbers by VMG on Sunday January 13, 2013 @04:33PM (#5051938)
you can also just use Number() to be safe
Re:Be careful with JS numbers by gren on Sunday January 13, 2013 @04:52PM (#5052019)
How is it different?
Re:Be careful with JS numbers by Hovertruck on Sunday January 13, 2013 @06:00PM (#5052256)
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