How to convert a string to a number in JavaScript?

Total
0
Shares

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

Open Live Demo