Skip to content
Advertisements

JavaScript parseInt()

The JavaScript parseInt method returns the string parameter that it receives based on the specified number of system bases and returns an integer. The parseInt method is one of the basic functions of JavaScript and is not linked to any object.

parseInt(String, number system)
  • “String”: The string to convert.
  • “Number System”: Number of 2, 8, 10 and 16 that represent number systems.

parseInt does the conversion assuming that the number of the character string is in the number system specified by the system. The numbers that can be specified as the number system are 2 for the binary system, 8 for the octal system, 10 for the decimal system and 16 for the hexadecimal system. If the number system is not specified, then parseInt does the following.

  • If the string starts with ‘0x’, the number system assumes hexadecimal.
  • If the string starts with ‘0’, it assumes the number system is octal.
  • If the string starts with one of the other digits, the decimal assumes.

NaN value is returned if the first character is not dialed.


Example 1:

<script type="text/javascript">
	document.write( parseInt("11", 16) + "<br/>");
	document.write( parseInt("11", 10) + "<br/>");
	document.write( parseInt("11", 8) + "<br/>");
	document.write( parseInt("11", 2) + "<br/>");
</script>

Output:

17
11
9
3

Example 2:

document.write( parseInt("11", 16) );    // 17
document.write( parseInt("FFF", 10) );   // NaN
document.write( parseInt("0xf", 8) );    // 0
document.write( parseInt("0xf", 0) );    // 15
document.write( parseInt("0xf") );       // 15
document.write( parseInt("10abc", 16) ); // 68284
document.write( parseInt("10abc", 0) );  // 10
document.write( parseInt("abc10", 0) );  // NaN

Output:

17
NaN
0
15
15
68284
10
NaN
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: