Converting to numbers
Learn to convert strings to numbers with parseInt, parseFloat and Number().
parseInt: String to integer
parseInt reads the integer at the start of a string. It walks until a non digit character and ignores the rest.
The second argument is the radix (base) that tells which number system to read in. Always pass 10 for the decimal system:
const quantity = parseInt("3 pens", 10);
// quantity = 3If you skip the radix JavaScript may read some strings as octal (base 8); always writing 10 explicitly is safer.
parseFloat and Number
parseFloat reads from the start of a string just like parseInt, but it also accepts a decimal dot. It stops at a non number character.
Number is stricter: the whole string must be a valid number. If there is junk at either end it returns NaN.
For example:
parseFloat("3.14try")→3.14Number("3.14try")→NaNNumber("42")→42
Exercise Convert strings to numbers
Assign parseInt("3", 10) to quantity and parseFloat("19.99") to price (both as const). Then log both with console.log.
Show example solution
const quantity = parseInt("3", 10);
const price = parseFloat("19.99");
console.log(quantity);
console.log(price);
Test yourself
-
What does parseInt("42px", 10) return?
console.log(parseInt("42px", 10));- NaN
- Throws an error
- 42
- 42px
Show answer
42 — Correct. parseInt reads from the start and stops at the non digit "px"; the result is 42.
-
Parse a hexadecimal value
const hex = parseInt("ff", ____);Show answer
const hex = parseInt("ff", 16); -
Match each method to its job
- parseInt
- Parses to an integer
- parseFloat
- Parses to a decimal
- Number
- Checks the whole string
- radix
- Number base (2, 10, 16)
-
What does Number("42px") return?
console.log(Number("42px"));- NaN
- 42
- 42px
- Throws an error
Show answer
NaN — Correct. Number checks the whole string; the "px" part is invalid so it returns NaN.