Convert a string to a number in JavaScript

habtesoft
2 min readMar 14, 2023

The parseInt() function is used to parse a string and return an integer. It takes two arguments - the string to parse and the radix (which specifies the base of the number system to use). If the radix is not specified, parseInt() assumes it to be 10.

Not a Medium member? Read this article here

Here’s an example of using parseInt() to convert a string to a number:

const str = "123";
const num = parseInt(str);
console.log(num); // Output: 123

The parseFloat() function is used to parse a string and return a floating-point number. It works in a similar way to parseInt(), but can handle decimals.

Here’s an example of using parseFloat() to convert a string to a number:

const str = "3.14";
const num = parseFloat(str);
console.log(num); // Output: 3.14

It’s worth noting that both parseInt() and parseFloat() will return NaN (Not a Number) if they are unable to parse a valid number from the string.

Here’s an example of using parseInt() with a radix:

const str = "1010";
const num = parseInt(str, 2); // radix of 2 specifies binary number system
console.log(num); // Output: 10

And here’s an example of using parseFloat() with a string containing non-numeric characters:

const str = "3.14abc";
const num = parseFloat(str);
console.log(num); // Output: 3.14

In summary, you can convert a string to a number in JavaScript using the parseInt() or parseFloat() functions, depending on whether you want to convert to an integer or floating-point number.

--

--

habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat