Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

What does JavaScript convert that 0 radix to?

like image 517
Hommer Smith Avatar asked Oct 28 '25 00:10

Hommer Smith


2 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'.

like image 167
Mykola Prymak Avatar answered Oct 29 '25 13:10

Mykola Prymak


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.
like image 22
Aniket Kulkarni Avatar answered Oct 29 '25 13:10

Aniket Kulkarni