Skip to main content
0 reactions

How to Turn Text into a Whole Number with parseInt() in JavaScript

Card titled parseInt() in JavaScript, labelled JavaScript basics, with four ticked lines: 42 as text gives 42, 4 stars gives 4, 4.9 gives 4, and five gives NaN.

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

SyntaxJavaScript
parseInt(text, radix)
  • text: the string to read. Spaces at its start are skipped.
  • radix: optional, the number base. Leave it out, or write 10, for everyday numbers.
  • The result: the whole number at the start of the text, or NaN when the text doesn’t start with one.

See parseInt() (opens in a new tab) on MDN.

Prerequisites

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

rating.jsJavaScript
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

TerminalBash
node rating.js
OutputPlain text
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

MistakeWhat happensDo this instead
Expecting decimals from parseInt('4.9')You get 4: the part after the dot is droppedUse 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 tooCheck 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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments