Convert a String to an Integer in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 31 20212 min read

banner

Photo by Dan Russo

Convert a String to an Integer in JavaScript #

Use the parseInt() function to convert a string to an integer, e.g. parseInt(myNumber, 10). The second parameter the function takes is the base, and should be set to 10. The parseInt function parses the string to an integer and returns the result. If the string can't be parsed, NaN is returned.

index.js
const str = '010'; console.log(parseInt('37', 10)); // ๐Ÿ‘‰๏ธ 37 console.log(parseInt('37.5', 10)); // ๐Ÿ‘‰๏ธ 37 console.log(parseInt('-37', 10)); // ๐Ÿ‘‰๏ธ -37 console.log(parseInt('test', 10)); // ๐Ÿ‘‰๏ธ NaN console.log(parseInt('123test', 10)); // ๐Ÿ‘‰๏ธ 123

We used the parseInt function to parse a string to an integer.

The function takes 2 parameters:

  1. the string we want to parse to an integer
  2. the radix - this doesn't default to 10 in older browsers, so it's safer to explicitly provide it

If the first argument is not a string, the function will convert it to a string and try to parse it to an integer.

If successful, the integer is returned, otherwise NaN (not a number) is returned.

Note that the type of NaN is number.
index.js
console.log(typeof NaN); // ๐Ÿ‘‰๏ธ "number"

So if you want to check if the function returned a valid integer, do this instead.

index.js
const value = parseInt('test', 10); if (!Number.isNaN(value)) { console.log('โœ… we have a valid integer'); } else { console.log('โ›”๏ธ we have an NaN value'); }

We negated the return value of the Number.isNaN function, to check if the value is a valid integer.

If the parseInt function didn't return NaN (not a number), we can conclude that we have a valid integer.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee