This page looks best with JavaScript enabled

Convert Strings to Numbers in Javascript

 ·   ·  ☕ 2 min read

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.

1
2
3
4
5
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.

1
2
3
4
5
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.

1
2
3
4
5
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things