Friday, 24 September 2010

Javascript parseInt() gotcha

Recently I was working on JS code that should convert strings (2 chars) into numbers from range 0-9 as presented below:

'00' => 0
'01' => 1
'02' => 2
'03' => 3
'04' => 4
'05' => 5
'06' => 6
'07' => 7
'08' => 8
'09' => 9

I used parseInt() function to achieve that. I was surprised to discover that the variables values where a bit different than I expected:
var i = parseInt('00'); // i = 0
i = parseInt('01'); // i = 1
i = parseInt('02'); // i = 2
i = parseInt('03'); // i = 3
i = parseInt('04'); // i = 4
i = parseInt('05'); // i = 5
i = parseInt('06'); // i = 6
i = parseInt('07'); // i = 7
i = parseInt('08'); // i = 0
i = parseInt('09'); // i = 0

Solution
As you can see parseInt('08') and parseInt('09') returned 0. This is because this function treats strings beginning with '0' as octal numbers and strings beginning with '0x' as hexadecimal numbers. To fix that you can provide the radix to use as a second parameter (optional):

var i = parseInt('00', 10); // i = 0
i = parseInt('01', 10); // i = 1
i = parseInt('02', 10); // i = 2
i = parseInt('03', 10); // i = 3
i = parseInt('04', 10); // i = 4
i = parseInt('05', 10); // i = 5
i = parseInt('06', 10); // i = 6
i = parseInt('07', 10); // i = 7
i = parseInt('08', 10); // i = 8
i = parseInt('09', 10); // i = 9