Skip to main content

Posts

Showing posts from January, 2012

Beware of JavaScript's parseInt function - 010 does not equal 10...

I use JavaScript & jQuery quite a bit in my day job helping to add a bit of 'shiny' to our web applications. One feature that I added recently kept a track of the percentages that you had typed in the form.  It told you at the bottom of the page how much percentage you had left - I used JavaScript's parseInt function to help me in this respect. As the application passed through system test it was found that if you typed '020' as a percentage my application said that you had 84% left to assign rather than the expected 80% - any ideas what's going on? Yes that's right - the leading zero was causing parseInt to treat the number as an octal (base 8) number and so 020 was two lots of 8 = 16. It appears that this octal recognition is being deprecated but who knows when it will actually go so for now I've had to add ", 10" (i.e. a decimal radix) to the end of all of my parseInt calls: parseInt(percentage, 10); Double check any code that you