parseInt() reads an integer from the beginning of a string. When the base matters, pass a radix from 2 to 36; using 10 makes decimal intent explicit.
console.log(parseInt("42", 10)); // 42
console.log(parseInt("101", 2)); // 5
parseInt(string, radix)The radix is an integer between 2 and 36. For ordinary decimal text, use parseInt(text, 10).
console.log(parseInt("2", 10)); // 2
console.log(parseInt("2.4", 10)); // 2
console.log(parseInt("-3.9", 10)); // -3
console.log(parseInt(" 50 ", 10)); // 50
console.log(parseInt("Hello", 10)); // NaN
console.log(parseInt("5ab", 10)); // 5
console.log(parseInt("ab5", 10)); // NaN
console.log(parseInt("1e3", 10)); // 1, not 1000
console.log(parseInt("101", 2)); // 5
console.log(parseInt("15", 8)); // 13
console.log(parseInt("15", 16)); // 21
console.log(parseInt("5", 2)); // NaN
If no radix is supplied, a leading 0x or 0X is recognized as hexadecimal. Do not teach or depend on a leading zero as an octal signal. For clarity and portability, supply the radix when parsing known-base text.
console.log(parseInt("0xA")); // 10
console.log(parseInt("011")); // 11 in modern JavaScript parsing
console.log(parseInt("011", 8)); // 9
console.log(parseInt("42px", 10)); // 42
console.log(Number("42px")); // NaNUse Number() when the entire input must be numeric. Use parseInt() when reading an integer prefix is intentional.
console.log(parseInt("19.95", 10)); // 19
console.log(parseFloat("19.95")); // 19.95See parseFloat() when fractional values are required.
parseInt() is a string parser. For a Number that you want to truncate toward zero, use Math.trunc(). Converting very large or very small Numbers to strings before parsing can also produce unexpected results because scientific notation may be used.
console.log(Math.trunc(-3.9)); // -3
parseInt() returns a Number, so integer values beyond the safe-integer range may lose precision. For integer text that must remain exact at arbitrary size, consider BigInt() when appropriate.
const raw = document.getElementById("age").value;
const age = parseInt(raw, 10);
if (Number.isNaN(age)) {
console.log("Enter a valid integer");
}
See numeric validation, NaN, array toString(), and base conversion.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.