Here are three common ways:
var myNumber = +myString; // coerce string to number
var myFloat = parseFloat(myString); // parse as floating point number
var myInt = parseInt(myString, 10); // parse as a base-10 integer
Documentation:
+ operator - mdn msdn
parseFloat() method - mdn msdn
parseInt() method - mdn msdn
Each of these techniques have their own quirks. Because of the dynamic nature of JavaScript, type conversion is not simple.
parseInt()
parseInt() produces either an integer or a NaN by reading the digits from left to right. If your string contains only numeric digits, and you are using a browser that supports ECMAScript 5 (IE8 and older do not), It is very straightforward - you get those digits as a number in base 10. In IE8 or older, if the first digit is 0, you'll get the number in octal. Eg, parseInt("010") returns 10 in modern browsers and 8 in older browsers. To correct for this, always specify the radix in the second parameter. parseInt("010", 10) always returns 10, regardless of browser version.
Parsing stops at the first non-digit character. So, parseInt("4 donuts") returns 4 as does parseInt("4,000"). If the first character in the string is not a digit or + or -, you will get NaN, so you can't parse "$5".
If the string starts with 0x it is treated as Hexadecimal (base 16). parseInt("0x10") returns 16. Same thing if you explicitly specify base 16 with the radix: parseInt("10", 16).
parseFloat()
parseFloat() is similar to parseInt(). The differences are that parseFloat() only works with base 10, and, obviously, it produces a floating point number.
Addition operator (+)
In JavaScript, a string can be used as a number. When a JavaScript construct accepts a number and gets something else (such as a string), it very typically tries to "coerce" it to a number. One case where we see this behavior is the + operator. In some ways, coercion is more strict than parsing -- The entire string must be numeric, not just the beginning, or else it returns NaN. But, in another way, it's less strict -- an empty or whitespace string returns 0 when coerced to a number, but returns NaN when parsed.
Besides the addition operator, other ways to coerce a string to a number include:
- Use the
Number() constructor as a function
- Pass a string to a method that accepts a number, eg
Math.floor("10")
- Use a string with an arithmetic operator:
var string = "10";
var num = string * 1;
var num = string / 1;
Get the full details about how a string is coerced to a number in the ECMAScript Spec, Section 9.3.1.