How to convert strings to numbers in JavaScript?

To convert a string to a number, use the JavaScript function parseFloat (for conversion to a floating-point number) or parseInt (for conversion to an integer).

Syntax:parseFloat('string')
parseInt( 'string' [, base] )

The argument of parseFloat must be a string or a string expression. The result of parseFloat is the number whose decimal representation was contained in that string (or the number found in the beginning of the string). If the string argument cannot be parsed as a decimal number, the results will be different in different browsers (either 0 or NaN).

The first argument of parseInt must be a string or a string expression. The result returned by parseInt is an integer whose representation was contained in that string (or the integer found in the beginning of the string).
The second argument (base), if present, specifies the base (radix) of the number whose string representation is contained in the string. The base argument can be any integer from 2 to 36. If there is only one argument, the number base is detected according to the general JavaScript syntax for numbers. Strings that begin with 0x or -0x are parsed as hexadecimals; strings that begin with 0 or -0 are parsed as octal numbers. All other strings are parsed as decimal numbers. If the string argument cannot be parsed as an integer, the results will be different in different browsers (either 0 or NaN).

Note:
If you prompt the user for a number, using the prompt function, what you actually get is a string that contains the “number”. This is also the case, if you look at the value of a text field on a form. This means that before you can use the number, you must convert it to a “real” number.
JavaScript will convert a string to a number for you automatically, however it may not handle it properly, especially if there is a ‘+’ operator involved. Remember the ‘+’ operator adds numbers and comcatenates strings.

I’m relatively new to seriously using JavaScript, I had previously tried to use PHP to do everything. The biggest problem I have found I run into using JavaScript is not converting strings to numbers when I should. I can’t tell you how much time I’ve wasted because I didn’t notice 12 + 12 was adding up to 1212 in one of my programs.