JavaScript: Convert a string into a number.

This is a short tutorial on how to convert a string into a number using JavaScript. In this guide, I will show you how to parse a string into an int or a float value.

Let’s jump right in and take a look at a few examples!

Converting a JavaScript string into an int.

If your number does not contain decimal places, then you can simply convert the string into an integer value:

In the snippet above, we used the native parseInt function to parse our string and return the integer value.

However, what if our string contains a number that has decimal places?

If you run the code above, you will see that JavaScript has removed our decimal places and rounded the number down.

If you would prefer to the round the number to the closest integer, then you can use the Math.round method like so:

The code above results in the integer 13 being returned. Note that you do not need to create a Math object in order to call the round method. This is because round is a static method.

Converting a JavaScript string in a float value with decimals.

If you have decimal places that you would like to keep, then you will need to convert the string into a float value:

Here, we were able to convert our string into a float value by using the native parseFloat function. As a result, we kept our two decimal places.

Note that if the parseFloat function fails to parse the string into a float, it will return a NaN value. In case you didn’t already know, NaN is an acronym for “Not a Number”.

This will occur if you do something silly like this:

If you run the code above and look at your browser console, you will see “NaN” being printed out.

Older browsers and the radix parameter.

There is one caveat with the parseInt and parseFloat functions. Before 2016, they both required a second mandatory parameter called the radix. As a result, older outdated browsers may cause you conversion problems. Code quality and lint tools may also raise a warning.

To guard against this, simply provide the number 10 as the second parameter:

Note that we usually use 10 as the radix because that tells the parseInt and parseFloat functions to use the base 10 number system. In older browsers, if you fail to provide the radix parameter, the function will default to 8. An 8 radix represents the octal system, which is probably not what you want to use.

Facebook Comments