parseInt in JavaScript

As per the MDN document parseInt() method-

Parses a string argument and returns an integer of the specified radix or base.

SyntaxparseInt(string, radix);

Parameter 1 (string) –

The value to parse.

Parameter 2 (radix) –

An integer that represents the radix of the above mentioned string, it is an optional parameter to be passed, however it is strongly recommended to set a one to avoid confusion.

Return type –

integer

If the radix parameter is missing then JavaScript assumes the following:-

  • If the string begins with “0x”, the radix is 16 (hexadecimal)
  • If the string begins with “0”, the radix is 8 (octal) or 10 (decimal). This feature is browser dependent. ECMAScript 5 specifies to use 10, but not supported in many browsers so keeping your hands clean it is always a good practice to mention radix.
  • If the string begins with any other value, the radix is 10 (decimal)

Now Let us consider some examples about its implementation and check return values-

  1. document.write(parseInt()); // return NaN
  2. document.write(parseInt( )); // return NaN
  3. document.write(parseInt(01)); // return 1 as 0*81 + 1*80
  4. document.write(parseInt(010)); // return 8 as 0*82 + 1*81 + + 0*80

Explanation – As mentioned If a number starts with 0 the method will take radix as octal or 8 by default. [This is the case in my browser test as mentioned it may also take 10(decimal) depending upon ECMAScript adaption]

Moving to next level, lets us cover some string examples as well –

  1. document.write(parseInt(“a”)); // return NaN
  2. document.write(parseInt(“7a”)); // return 7 surprised!!
  3. document.write(parseInt(“017s”)); // return 15 as 0*82+1*8*1+7*80

Now I believe you are in a position to understand some dirty examples as well. Its time to check radix involvement now –

    • document.write(parseInt(14,8)); // return 12 as 1*81 + 4*80
    • document.write(parseInt(“14”,8)); // return 12, self explanatory if u followed above examples well
    • document.write(parseInt(“A”,16)); // return 10, interesting isn’t it!!! well this is because A is considered as 10 in HEXADECIMAL system, so the string will be consider as 10*160
    • document.write(parseInt(“AB”,16)); // return 171, as mentioned in above example-> A as 10, B as 11, so it will go like this, 10*161+ 11*160
    • document.write(parseInt(“ABC”,16)); // return 2748 as 10*162 + 11*161+ 12*160
    • document.write(parseInt(“S1”,16)); // return NaN, as S does not belongs to HEXADECIMAL code

NOTE– In above example a and A are at same levels so document.write(parseInt(“abc”,16)); will output the same 2748 on the same grounds.

Hope you are now in a better situation to actually answer weird behaviors in parseInt() method.

Let me know your feedback as always πŸ™‚

Advertisements