USING PARSEINT() AND PARSEFLOAT()

The syntax for parseInt() is:

parseInt(string, radix)

The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of 10 indicates to the JavaScript interpreter that it needs to convert to a decimal number (base 10); a radix of 8 indicates an octal number (base 8); a radix of 16 denotes a hexadecimal number (base 16); and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

Parse is a linguistic term that means to break into smaller pieces for analysis.

If parseInt encounters a character that isn't a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. The parseInt function truncates (cuts off) numbers to integer values. Leading and trailing spaces are allowed.

If the radix isn't specified or is specified as 0, JavaScript assumes the following:

  • If the input string begins with "0x", the radix is 16 (hexadecimal).
  • If the input string begins with "0", the radix is 8 (octal).
  • If the input string begins with any other value, the radix is 10 (decimal).
  • If the first character cannot be converted to a number, parseInt returns NaN (not a number).

The parseFloat function is similar to parseInt. parseFloat() parses a string and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), numeral (0-9), decimal point, or exponent, it returns the value up to that point and ignores that character and all succeeding characters. If the first character can't be converted to a number, it returns NaN (not a number).

Unlike parseInt(), parseFloat() doesn't need a radix value -- it automatically strips leading zeros.