How to convert a string to a number in Javascript

There are several ways to convert a string to a number in Javascript. In this article, we’ll take a look at some of the most common ones and cover the pitfalls and advantages of each.

1) parseInt

parseInt(string, radix);

The most common method used to convert a string to a number is parseInt(). It takes two parameters, string and radix. The first parameter is the string you want to convert to a number. The second parameter, radix, is the base number system you want to convert the string to. It should usually be 10, which represents the decimal system.

Notes:

  • If you don’t pass in a radix, parseInt will attempt to determine the base of the number you passed in automatically, which can lead to unwanted behavior. If the number you pass in starts with a 0 and you don’t pass in a radix, parseInt will attempt to convert your number to octal.
  • parseInt() automatically cuts off decimal numbers (floats) without rounding them.

Example usage:

https://gist.github.com/2504319

2) parseFloat

parseFloat(string)

Another useful method is parseFloat. It converts from a string to a floating point number (a decimal).

Notes:

  • If the string passed in starts with a non-numeric character, parseFloat will return NaN.
  • If multiple strings are passed in, parseFloat will return the first float it parses out of the string.

Example usage:

https://gist.github.com/2504818

3) Multiplying by 1

string*1

This is an interesting and unorthodox method to parse a number. Similiar to parseFloat, it returns a number preserving decimal places (a floating point value). However, it is very strict and only accepts a string that contains only numeric characters and only one number; anything else returns NaN.

Notes:

  • string*1 will only parse one number in a string; if there is more than one it returns NaN.
  • Unlike parseInt, it ignores any zeroes preceding a number; they will be stripped out in the return value.
  • string*1 is slightly faster than parseFloat in certain browsers, although the difference is negligible.

Example usage:

https://gist.github.com/2504917

2 thoughts on “How to convert a string to a number in Javascript”

  1. elvin says:

    what about prepending the string with plus. number = +string;

    1. Silverware says:

      number = 0 + string;
      This is my current favorite way of doing things.