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.
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?
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
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);