How to convert a string to a number in JavaScript?


It is essential to convert a string to a number in javascript in order to do arithmetic calculations on them. Sometimes when we fetch data from database, the numeric values gets converted into string. Now, if we try to do arithmetic sum on strings in javascript, they will get concatenated. To solve this issue, we need to convert strings to number and then perform calculations.

JavaScript has parseInt() function for that. But first check if the provided value is a string or number or something else. You can use typeof operator for that. If you won’t check then your code might fail. Also you can use isNaN() for checking if a value is a number.

const convertStringToNumber = (stringToConvertToNumber) => {

  if(typeof stringToConvertToNumber === 'number'){

    return stringToConvertToNumber;

  } else if(typeof stringToConvertToNumber === 'string'){
    const convertedNumber = parseInt(stringToConvertToNumber);

    return convertedNumber || convertedNumber === 0 ? 
           convertedNumber : false;

  } else {
    return false;

    Tweet this to help others

This method is type safe and will not create any error. You will either get the numeric value of the string or you will get false.

Live Demo

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

React convert JSON to CSV

React convert JSON to CSV using JSONToCSVConvertor function. Suppose you have a table (GUI react table tool) and you want to export it into excel, then this function will come…
View Post

.map is not a function

map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables…
View Post