JavaScript provides the parseInt
function to convert strings into integers. However, it has some nuances that developers must understand to use it effectively.
parseInt
parseInt(string, radix);
string
: The value to be converted.
radix
: The base of the numerical system (optional but highly recommended).
console.log(parseInt("42")); // Output: 42
console.log(parseInt("0037")); // Output: 37
console.log(parseInt("10", 2)); // Output: 2 (Binary to Decimal)
console.log(parseInt("A", 16)); // Output: 10 (Hexadecimal to Decimal
If the radix is not specified, JavaScript may misinterpret the number:
console.log(parseInt("08")); // Output: 8 (Modern JS assumes decimal)
console.log(parseInt("08", 10)); // Output: 8 (Explicitly decimal)
parseInt
stops parsing at the first non-numeric character:
console.log(parseInt("123abc")); // Output: 123
console.log(parseInt("abc123")); // Output: NaN (Not a Number)
Not specifying the radix
Assuming parseInt
rounds numbers
console.log(parseInt("10.9")); // Output: 10 (It truncates, not rounds)
parseInt
is a useful function in JavaScript but requires careful handling, especially with radix. Always specify the radix to avoid unexpected results!
For more JavaScript tips, visit Codercrafter Blogs. 🚀