JavaScript Number.parseInt(string, radix) function
The Number.parseInt(string, radix)
function in JavaScript is a static method used to parse a string argument and convert it into an integer. This function allows you to specify the base (radix) of the numeral system to use when parsing the string, making it versatile for various number systems.
Syntax:
string
: The string to be parsed. It can contain numeric characters and may include leading whitespace.radix
(optional): An integer between2
and36
that represents the base of the numeral system to be used. If omitted, the radix is inferred from the string.
Return Value:
- Returns the parsed integer if the string can be converted into a valid integer; otherwise, it returns
NaN
(Not-a-Number).
Key Characteristics:
Leading Whitespace: The function ignores leading whitespace in the string before attempting to parse the number.
Radix Parameter: The radix parameter specifies the base of the number system:
- Base 10: Decimal
- Base 2: Binary
- Base 8: Octal
- Base 16: Hexadecimal
- And so on, up to base 36.
Stops Parsing at Invalid Characters: Parsing stops when the function encounters a character that is not part of a valid integer for the specified radix after successfully reading the number.
NaN for Invalid Input: If the string cannot be converted into a valid integer, it returns
NaN
.
Example 1: Basic Usage
In these examples, the strings are successfully parsed into integers.
Example 2: Using Radix
Here, the radix parameter allows for correct interpretation of numbers in different bases.
Example 3: Handling Invalid Characters
Parsing stops at the first invalid character, returning a valid integer.
Example 4: Invalid Input
In these cases, the strings cannot be converted into valid integers, so the function returns NaN
.
Example 5: Edge Cases
- Radix Defaults: If the radix is not provided, the function may behave unexpectedly with certain strings:
- If the string starts with "0x" or "0X", it is treated as hexadecimal.
- If the string starts with "0" (and is not followed by "x"), it is treated as octal (in older versions of JavaScript; the behavior can vary in strict mode and modern implementations).
Summary:
- The
Number.parseInt(string, radix)
function is a versatile way to convert strings representing integers into actual integer values in JavaScript. - It allows you to specify the base of the numeral system, handles leading whitespace, and stops parsing at invalid characters.
- It returns
NaN
for non-numeric inputs and can behave differently based on the specified radix or lack thereof, making it essential to specify the radix explicitly for clarity and correctness.