.parseInt()
Published May 31, 2024
Contribute to Docs
In JavaScript, the .parseInt()
function converts a string into an integer. This function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Syntax
Number.parseInt(string, radix);
Number
: The JavaScript built-in object that serves as a namespace for numerical-related functions and constants.string
: The string to be parsed. The leading whitespace in the string is ignored.radix
: An optional parameter that specifies the base of the numeral system to be used for parsing. It is an integer between 2 and 36. If not provided, theradix
defaults to 10, except when the string starts with0x
or0X
, which indicates a hexadecimal number.
Example
The following example demonstrates some of the use cases of the .parseInt()
function:
// converting string to decimalconst x = Number.parseInt('100');console.log(x);// converting binary to decimalconst y = Number.parseInt('101', 2);console.log(y);//converting hexadecimal to decimalconst z = Number.parseInt('7F', 16);console.log(z);// unintended uses of parseInt() function:// radix must be between 2 and 36 inclusiveconst invalidRadix = Number.parseInt('123', 1);console.log(invalidRadix);// first character of string must be a numeric digitconst firstChar = Number.parseInt('*123');console.log(firstChar);
The above code will give the following output:
1005127NaNNaN
Note: The above example does not cover all possible situations or options. They are just a few examples that help illustrate the concept.
Codebyte Example
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.