To allow more flexible conversions, you can use parseInt( ) and parseFloat( ). These functions convert and return any number [color=red]at the beginning of a string[/color], ignoring any trailing non-numbers. parseInt( ) parses only integers, while parseFloat( ) parses both integers and floating-point numbers. If a string begins with "0x" or "0X", parseInt( ) interprets it as a hexadecimal number.[4] For example:
[4] The ECMAScript specification says that if a string begins with "0" (but not "0x" or "0X"), parseInt( ) may parse it as an octal number or as a decimal number. Because the behavior is unspecified, you should never use parseInt( ) to parse numbers with leading zeros, unless you explicitly specify the radix to be used!
parseInt( ) can even take a second argument specifying the radix (base) of the number to be parsed. Legal values are between 2 and 36. For example:
If parseInt( ) or parseFloat( ) cannot convert the specified string to a number, it returns NaN:
[4] The ECMAScript specification says that if a string begins with "0" (but not "0x" or "0X"), parseInt( ) may parse it as an octal number or as a decimal number. Because the behavior is unspecified, you should never use parseInt( ) to parse numbers with leading zeros, unless you explicitly specify the radix to be used!
parseInt("3 blind mice"); // Returns 3
parseFloat("3.14 meters"); // Returns 3.14
parseInt("12.34"); // Returns 12
parseInt("0xFF"); // Returns 255
parseInt( ) can even take a second argument specifying the radix (base) of the number to be parsed. Legal values are between 2 and 36. For example:
parseInt("11", 2); // Returns 3 (1*2 + 1)
parseInt("ff", 16); // Returns 255 (15*16 + 15)
parseInt("zz", 36); // Returns 1295 (35*36 + 35)
parseInt("077", 8); // Returns 63 (7*8 + 7)
parseInt("077", 10); // Returns 77 (7*10 + 7)
If parseInt( ) or parseFloat( ) cannot convert the specified string to a number, it returns NaN:
parseInt("eleven"); // Returns NaN
parseFloat("$72.47"); // Returns NaN