How do you convert a string to a number in JavaScript?
TL;DR
Use Number(value) when the whole string must represent a number. Use parseInt(value, radix) or parseFloat(value) when intentionally accepting a numeric prefix such as '12px'; they stop at the first invalid character. Check the result with Number.isNaN() or, for finite application values, Number.isFinite(). Remember that Number('') and Number(' ') are 0, so validate required input before conversion.
Using the Number() function
The Number() function converts a string to a number. It can handle both integer and floating-point numbers.
Using the parseInt() function
The parseInt() function parses a string and returns an integer. It can also take a second argument, the radix (base) of the numeral system to be used.
Using the parseFloat() function
The parseFloat() function parses a string and returns a floating-point number.
Using the unary plus operator (+)
The unary plus operator can be used to convert a string to a number. It is a shorthand method and works for both integers and floating-point numbers.
Handling non-numeric strings
If the string cannot be converted to a number, these methods will return NaN (Not-a-Number).
The conversion methods are intentionally different:
Always pass the radix to parseInt() when the expected base is known. Do not test for NaN with value === NaN; NaN is unequal to itself.
Further reading
- MDN Web Docs: Number()
- MDN Web Docs: parseInt()
- MDN Web Docs: parseFloat()
- MDN Web Docs: Unary plus (+)