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:

[gist]https://gist.github.com/2504319[/gist]

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:

[gist]https://gist.github.com/2504818[/gist]

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:

[gist]https://gist.github.com/2504917[/gist]

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

Leave a Reply

Your email address will not be published. Required fields are marked *