Let’s jump right in and take a look at a few examples!
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 would prefer to the round the number to the closest integer, then you can use the Math.round method like so:
//String value with decimal places. var str = '12.583'; //Round the number inside our string using Math.round var num = Math.round(str); //The result is 13, as 12.583 is closer to 13 than 12. console.log(num);
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.
If you have decimal places that you would like to keep, then you will need to convert the string into a float value:
//A JS string with decimal places. var str = '19.89'; //Convert the string into a float value //using the parseFloat function. var floatNum = parseFloat(str); //The result is 19.89 console.log(floatNum);
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:
//This code will result in a NaN value //being returned var floatNum = parseFloat('Hello'); //The result is NaN console.log(floatNum);
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:
//Example string var str = '393'; //Providing the radix param var num = parseInt(str, 10);
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.