Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Convert the string of any base to integer in JavaScript
The parseInt() function in JavaScript converts strings representing numbers in any base (2-36) to decimal integers. This is useful when working with binary, octal, hexadecimal, or other numeral systems.
Syntax
parseInt(string, radix);
Parameters
string ? The value to parse. If not a string, it's converted using the ToString method. Leading whitespace is ignored.
radix ? An integer between 2 and 36 representing the base of the numeral system. If omitted, defaults to 10 (except for strings starting with "0x" which default to 16).
Examples
Converting Different Bases to Decimal
console.log(parseInt("100", 10)); // Decimal (base 10)
console.log(parseInt("10", 8)); // Octal (base 8)
console.log(parseInt("101", 2)); // Binary (base 2)
console.log(parseInt("2FF3", 16)); // Hexadecimal (base 16)
console.log(parseInt("ZZ", 36)); // Base 36 (max base)
100 8 5 12275 1295
Common Base Conversions
// Binary to decimal
console.log(parseInt("1010", 2)); // 10
// Hexadecimal to decimal
console.log(parseInt("FF", 16)); // 255
console.log(parseInt("A1", 16)); // 161
// Octal to decimal
console.log(parseInt("777", 8)); // 511
10 255 161 511
Edge Cases and Important Notes
// Leading whitespace ignored
console.log(parseInt(" 42", 10)); // 42
// Stops parsing at first invalid character
console.log(parseInt("123abc", 10)); // 123
// Returns NaN for invalid input
console.log(parseInt("xyz", 10)); // NaN
// Always specify radix to avoid confusion
console.log(parseInt("010", 8)); // 8 (octal)
console.log(parseInt("010", 10)); // 10 (decimal)
42 123 NaN 8 10
Key Points
- Always specify the radix parameter to avoid unexpected behavior
- Valid digits depend on the base: binary (0-1), octal (0-7), decimal (0-9), hex (0-9, A-F)
- Base 36 uses digits 0-9 and letters A-Z (case insensitive)
- Parsing stops at the first invalid character for the specified base
- Returns
NaNif no valid number can be parsed
Conclusion
The parseInt() function with a specified radix parameter is the standard way to convert strings from any base (2-36) to decimal integers. Always include the radix parameter for predictable results.
Advertisements
