parseInt() global functionS2C Home « Globals « parseInt()

Global function that converts a string to an integer.

Description

Parses a string argument with an optional radix and attempts to return an integer.

Syntax

Signature Description
parseInt(string[, radix])Global function that converts a string to an integer.

Parameters

Parameter Description
stringThe string value you want to parse.
  • If the first non space character is not a numeral in the specified radix and cannot be converted to a number, parseInt returns NaN.
  • While parsing after the first non space character if the function encounters a character that is not a numeral in the specified radix it returns the integer value up to that point and ignores that character and all subsequent characters.
radixThe optional radix (number base) that pertains to the string value specified. Although optional for predictable results and clarity always specify a radix. When no radix is entered or is 0 the following is assumed by JavaScript:.
  • When input string begins with "0x" or "0X" the radix is assumed to be hexadecimal (radix set to 16).
  • When input string begins with "0" the radix may be assumed to be octal (radix set to 8). This is not standard and some implementations may not support this and set the radix to decimal (radix set to 10). For this reason alone you should always specify a radix when using the parseInt method.
  • When input string begins with any other number a decimal number base is assumed (radix set to 10).

Examples


Below are some examples of using the parseInt() function.


// Parsing string to integers.
var parsedValues = new Array(6);
parsedValues[0] = parseInt('17' 10); // Decimal base
parsedValues[1] = parseInt('10001', 2); // binary base
parsedValues[2] = parseInt('11', 16); // hex base
parsedValues[3] = parseInt('  17   ', 10); // within spaces
parsedValues[4] = parseInt('17.2345', 10); // decimal
parsedValues[5] = parseInt('abcdef', 10); // invalid
alert(parsedValues);

Press the button below to action the above code:


Related Tutorials

JavaScript Intermediate Tutorials - Lesson 6 - More Maths Functions

go to home page Homepage go to top of page Top