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)

One thought on “javascript’s parseInt is pretty evil”

  1. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *