In JavaScript, the parseInt() function is used to parse a string and convert it into an integer. It takes two arguments: the string to be parsed and an optional radix (base) indicating the numeral system to be used.
Syntax:
parseInt(string, radix)
- string: The string to be parsed into an integer.
- radix (optional): An integer between 2 and 36 that represents the numeral system to be used for parsing the string. If not specified, JavaScript assumes the radix to be 10.
Examples:
1. Basic Usage:
let str = "42"; let num = parseInt(str); console.log(num); // Output: 42
2. With Radix:
let str = "1010"; let num = parseInt(str, 2); // Parse as binary console.log(num); // Output: 10
3. Parsing Non-Integer Strings:
let str = "42.75"; let num = parseInt(str); console.log(num); // Output: 42
4. Using Radix for Hexadecimal:
let hexStr = "0xFF"; let num = parseInt(hexStr, 16); // Parse as hexadecimal console.log(num); // Output: 255
Explanation:
- The parseInt() function parses a string from left to right until it encounters a character that is not a valid digit in the specified radix. It then returns the integer value parsed up to that point.
- If the string starts with "0x" or "0X", it's interpreted as a hexadecimal number. Otherwise, it's interpreted as a decimal number by default.
- If the radix is not specified, or it is 0, JavaScript assumes a radix of 10 unless the string starts with "0x" or "0X" (in which case it's parsed as hexadecimal).
Use Cases:
- Converting User Input: Parse user-entered strings into integers for processing or validation.
- Working with Different Radices: Parse strings representing numbers in different numeral systems, such as binary, octal, or hexadecimal.
- Extracting Numbers from Strings: Extract numerical values embedded within strings for further manipulation or computation.
The parseInt() function is a useful tool for converting strings to integers in JavaScript, providing flexibility in handling different types of numerical data.
Code Compiler Link: https://app.singhteekam.in/codecompiler/