Convert Strings to Numbers in Javascript

There are multiple ways to convert a given string to a number - so, which one to use and where?

You would have also seen the more generic post on how to cast value from one type to another. But it may not be so apparent on which option to pick when you need to get numbers from a given string.

The first approach is my preferred one.

console.log(Number("hello")); // NaN
console.log(Number("abc123")); // NaN
console.log(Number("123abc")); // NaN
console.log(Number("123")); // 123
console.log(Number("123.12")); // 123.12

The values returned by Number evaluate to true or false as expected. You could easily check for valid numbers and abandon operation if the string is not a number.

The second approach is very similar to the above, except it provides an integer. However, you need to be careful about strings that start with numbers - parseInt extracts those numbers to provide a valid number even though the complete string is not a number.

console.log(parseInt("hello")); // NaN
console.log(parseInt("abc123")); // NaN
console.log(parseInt("123")); // 123
console.log(parseInt("123.12")); // 123
console.log(parseInt("123abc")); // 123

The third approach is to use parseFloat, which behaves exactly like parseInt except that it returns floating point numbers.

console.log(parseFloat("hello")); // NaN
console.log(parseFloat("abc123")); // NaN
console.log(parseFloat("123")); // 123
console.log(parseFloat("123.12")); // 123.12
console.log(parseFloat("123abc")); // 123

I prefer using Number almost all the time since I typically do not want half-strings to be evaluated as numbers.

comments powered by Disqus