How can I convert a string to a number without confusing zero and invalid input?
Quick answer
Use Number(text) to convert the string, then test the result with Number.isNaN(value). Don’t use if (!value) to detect failure: both zero and NaN are falsy. Also choose an explicit rule for empty or whitespace-only input, because Number() converts those strings to zero. If your application treats empty input as missing, check for it before converting.
The question, the details, the next step.
A practical checklist
Decide whether empty and whitespace-only strings count as missing or should convert to zero.
Convert the input with
Number(text).Use
Number.isNaN(value)to identify a failed conversion.Keep success status separate from the numeric value so zero remains valid.
Check representative numeric, zero, blank, whitespace, and invalid inputs.
A few more useful answers
Does `Number.isNaN(Number(""))` detect an empty string?
No. Number("") produces zero, so Number.isNaN() returns false. Check for empty input separately if your application should reject it.[S1]
Why use `Number.isNaN()` instead of checking whether the value is falsy?
A falsy check treats valid zero and NaN alike. After conversion, Number.isNaN(value) specifically detects the NaN result.[S2]
Sources
References used for this guide.
- [S1] Number — JavaScript | MDN developer.mozilla.org · Checked
- [S2] NaN — JavaScript | MDN developer.mozilla.org · Checked
