javascript’s parseInt is pretty evil
Javascript uses the + symbol for both addition and concatenation. This means that if you want to add a numeric value to data pulled from a user, you need to cast it to being a numeric type, like for instance an Int. Makes sense, so I use the parseInt function to cast with. OK, that’s fine so here is the kicker, if you pass it “09″ it generates the value 0, not 9.
Hrmm, well that’s odd. If you pass in “9″ it returns 9, but if you pass in “09″ you get 0. I’m lucky I caught that in testing. It turns out that if you lead with a 0 then parseInt interprates as the value as an octal number. There is a way to deal with it though, you can pass in a second variable telling it what base the numbers it should be reading are.
So really you want parseInt(var, 10) not parseInt(var)
1 Comment to javascript’s parseInt is pretty evil
Leave a comment
Pages
Archives
- April 2012
- March 2012
- January 2012
- December 2011
- November 2011
- September 2011
- August 2011
- July 2011
- June 2011
- May 2011
- March 2011
- February 2011
- January 2011
- November 2010
- May 2010
- March 2010
- January 2010
- December 2009
- October 2009
- September 2009
- August 2009
- July 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
I usually subtract zero (e.g. var-0) to implicitly convert the value to a number, but parseInt looks more readable. Good to know about the leading zero issue.
Is there ever a case where anyone should assume a value to be octal? Seems peculiar, doesn’t it?