Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript parseInt() function

JavaScript parseInt() function

Function Reference JavaScript Global Functions


Definition and Usage

The parseInt() function parses a string and returns an integer.

When the radix parameter is 0, or not set, parseInt() determines the base from the string.

When the radix parameter is omitted, JavaScript uses the following default base:

Syntax

parseInt(string, radix)

Parameters Description
string Required. The string to be parsed.
radix Optional. The base of the number to parse. A value between 2 and 36.

Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the parseInt() function


Tips and Notes

Note: Only the first number in the string is returned.

Note: Leading and trailing spaces are allowed.

**Note:** If the first character of the string cannot be converted to a number, parseInt() returns NaN.

**Note:** When a string starts with "0", older browsers use octal base by default. ECMAScript 5 uses decimal base by default.


Example

Example

We will use parseInt() to parse different strings:

document

.

write

(

parseInt

(

"

10

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

10.33

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

34 45 66

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

60

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

40 years

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

He was 40

"

)

"


"

)

;

document

.

write

(

"


"

)

;

document

.

write

(

parseInt

(

"

10

"

,

10

)

"


"

)

;

document

.

write

(

parseInt

(

"

010

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

10

"

,

8

)

"


"

)

;

document

.

write

(

parseInt

(

"

0x10

"

)

"


"

)

;

document

.

write

(

parseInt

(

"

10

"

,

16

)

"


"

)

;

The example above produces the following output:

Try it »

**Note:** Older browsers use an older version of ECMAScript (versions below 5 use octal by default when a string starts with "0", while ECMAScript 5 uses decimal), so parsing ("010") will output 8.


Function Reference JavaScript Global Functions