JavaScript radix

The optional radix parameter for JavaScript parseInt(string,radix) function is often overlooked and can lead to some difficult problems when not specified. If you are in doubt, and only use/expect decimal numbers, you SHOULD set it to 10.

This might go undetected for a very long time, until someone decides to prefix their value with a zero or zero and an ‘x’ and your code interprets it with something completely different. This behavior can be different based on the browser used due to changes in the EcmaScript definition and support of ‘octal’.

Here’s why…

Radix can be any number from 2-36 to define the number system.

  • 2 = binary (0-1)
  • 8 = octal (0-7)
  • 10 = decimal (0-9)
  • 16 = hexadecimal (0-F, where… 0-9,A=10,B=11,C=12,D=13,E=14,F=15)

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with “0x” or “0X”, the radix is 16 (hexadecimal)
  • If the string begins with “0”, the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

In all cases, the following is observed:

  • Leading and trailing spaces are allowed,
  • If the first character cannot be converted to a number, parseInt() returns NaN.
  • Only the first number in the string is returned.

REFERENCES: