How do you convert a string to a number?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
Four common options, and they disagree on the interesting inputs.
Number("42"); // 42
parseInt("42", 10); // 42
parseFloat("42.5"); // 42.5
+"42"; // 42
Where they differ
| Input | Number() | parseInt() | parseFloat() |
|---|---|---|---|
"42px" | NaN | 42 | 42 |
"3.9" | 3.9 | 3 | 3.9 |
"" | 0 | NaN | NaN |
" 12 " | 12 | 12 | 12 |
null | 0 | NaN | NaN |
"1e3" | 1000 | 1 | 1000 |
Number() is strict: the whole string must be a valid number, or you get NaN. The parse* functions are lenient — they read from the start and stop at the first character that does not fit, which is why "42px" becomes 42.
Pick by intent
Use Number() (or +) when the input should be a clean number and anything else is an error — form fields, API payloads. Use parseInt/parseFloat when you are deliberately extracting a number from text, such as "16px" from a computed style.
Always pass the radix to parseInt
parseInt("08"); // 8 today, but relies on default behaviour
parseInt("08", 10); // 8, explicitly decimal
parseInt("ff", 16); // 255
Validate the result
NaN propagates silently through arithmetic, so check before using the value:
const n = Number(input);
if (Number.isNaN(n)) return; // reject
if (!Number.isFinite(n)) return; // also rejects Infinity
Two traps worth remembering: Number("") is 0, not NaN, so an empty field can silently become zero. And integers beyond Number.MAX_SAFE_INTEGER lose precision — use BigInt("9007199254740993") for identifiers and large counts.
