Why parseInt(x,0) is the same as parseInt(x, 10)?

Viewed 844

Why is parseInt('60', 10) the same as parseInt('60', 0)?

What does JavaScript convert that 0 radix to?

4 Answers

From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)

If the radix is undefined, 0, or unspecified, JavaScript assumes the following:

If the input string begins with "0x" or "0X" (a zero followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.

If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

If the input string begins with any other value, the radix is 10 (decimal).

So the result depends on the browser if parsed input starts from '0'.

From the docs

If the radix is undefined, 0, or unspecified, JavaScript assumes the following:

  • If the input string begins with "0x" or "0X" (a zero followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
  • If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

parseInt(string, radix);

string:

  • The value to parse. If this argument is not a string, then it is converted to one using the ToString abstract operation. Leading whitespace in this argument is ignored.

radix

  • An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the string. Be careful — this does not default to 10.

From the ECMAScript® 2018 Language Specification (ECMA-262, 9th edition, June 2018):

If radix is undefined or 0, it is assumed to be 10 except when the number begins with the code unit pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the code unit pairs 0x or 0X.

Specifically steps 6, 8 and 9 say:

6 - Let R be ? ToInt32(radix).

8 - If R ≠ 0,...

9 - Else R = 0, Let R be 10.

So when radix == 0, it will always be replaced with 10, assuming a compliant browser.

As per the documentation, if radix is undefined or 0, it is assumed to be 10. so,

parseInt('60', 10) = (0 * 10 ^ 0) + (6 * 10 ^ 1) = 60 
     and 
parseInt('60', 0) = (0 * 10 ^ 0) + (6 * 10 ^ 1) = 60 
Related