jquery parseInt() without radix may cause a problem!

Background: The parseInt() function parses a string and returns an integer.

Syntax: parseInt(string, radix) 

stringRequired. The string to be parsed
radixOptional. A number (from 2 to 36) that represents the numeral system to be used

Radix parameter becomes important if your string input starts with 0 or 0x.
If you are using parseInt("010") and expecting output as 10, then you are wrong!
Because, parseInt at back end will consider any number starting with 0 as octal number so the output of "010" will be 8! Similarly any number starting with 0x will be considered as hex number, e.g. parseInt("0x10") will result to 16!

If you want to get decimal number always then use radix parameter.
So, parseInt("010",10) will tell parseInt to consider "010" as decimal so as to give output as 10.
Similarly you may use radix as 8 and 16 if you want octal and hex result respectively.


Post a Comment