Casting Datatypes

Main Page | Session 12 Index | Assignment Operators | Confirm Method


JavaScript includes a built-in function called parseInt() which is used to convert, or parse, string values to integer values for use in mathematical expressions.

The syntax of parseInt is:

parseInt(<string>, [<radix>])

where,

string
represents the value you want to parse, and
radix
is an integer that represents the radix (base) of the return value.

parseInt will attempt to return an integer of the radix specified. If the first character is not a number, parseInt returns the value "NaN", which means, not a number.

parseInt will convert the string until it encounters a non-numeric character, or the end of the string. If a non-numeric character is encountered, the character, and all subsequent characters are ignored, and parseInt returns the integer value parsed up to that point.

It the string represents a value greater than the largest integer value supported, parseInt returns the largest possible integer value. In 32-bit platforms, this is 2,147,483,647.

If the radix is zero or not specified, parseInt operates as follows:


This is an example of the code that is executed when the link below is selected. Enter the same number into the two prompt boxes and watch the difference between the values displayed in the alert boxes.

<SCRIPT LANGUAGE="JavaScript"> <!-- function parseIntTest() { alert(1 + prompt("Enter a number: ","")); alert(1 + parseInt(prompt("Enter a number: ",""))); } function parseFloatTest() { alert(1.5 + prompt("Enter a number: ","")); alert(1.5 + parseFloat(prompt("Enter a number: ",""))); } //--> </SCRIPT>

Test parseInt

Test parseFloat


Main Page | Session 12 Index | Assignment Operators | Confirm Method