parseInt() is a function built into JavaScript. It reads a text from the start, takes the whole number it finds there, and gives it back as a number you can calculate with. Anything after the number, such as a word, is ignored.
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
parseInt(text, radix)
text: the string to read. Spaces at its start are skipped.radix: optional, the number base. Leave it out, or write10, for everyday numbers.- The result: the whole number at the start of the text, or
NaNwhen the text doesn’t start with one.
See parseInt() (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
The Example
Six texts, such as a rating written as 4 stars, read by parseInt() in a file named rating.js.
Step 1: Write the Code
console.log(parseInt('42'));
console.log(parseInt('4 stars'));
console.log(parseInt(' 7 days'));
console.log(parseInt('4.9'));
console.log(parseInt('five'));
console.log(parseInt('4 stars') + 1);
Step 2: Run It
node rating.js
42
4
7
4
NaN
5
42 becomes the number 42. In 4 stars and 7 days, parseInt() skips the spaces at the start and stops at the first character that isn’t a digit, so it gives 4 and 7. 4.9 gives 4, because a whole number ends at the dot. five doesn’t start with a digit, so the result is NaN, which means “not a number”. The last line shows the result is a real number: 4 + 1 is 5.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Expecting decimals from parseInt('4.9') | You get 4: the part after the dot is dropped | Use parseFloat('4.9'), which gives 4.9 |
Using the result of a text that starts with a word, such as 'five' | You get NaN, and every sum with it gives NaN too | Check the result with Number.isNaN() before you use it |
FAQ
What is NaN?
A special number value that means the result isn’t a valid number. Number.isNaN(parseInt('five')) gives true.
Do I need the radix?
For everyday numbers, no. Without it, parseInt() reads the text as base 10, unless the text starts with 0x, which means base 16: parseInt('0x1A') gives 26. Write parseInt(text, 10) to be sure.
Conclusion
parseInt(text) gives the whole number at the start of a text. Check for NaN when the text might not start with a number, and use parseFloat() when you need decimals.
Additional Resources
- parseInt() (opens in a new tab) (MDN)
- NaN (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments