Parsing numbers — parseInt stops at the first bad character, Number() rejects the whole string¶
Level: 201 · for anyone who turns user input into numbers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: parseInt reads leading digits and stops, Number() and unary + want the whole string: parseInt("12px") is 12 but Number("12px") is NaN, Number("") is 0 but parseInt("") is NaN, and parseInt(0.0000005) is 5, because the number first becomes "5e-7".
Keywords: parseInt, parseFloat, radix
What the finished page will answer¶
- What do
parseInt,parseFloat,Number()and unary+return for"12px",""," 12 ","1e3","0x1f","0b101"andnull? - Why is
parseInt(0.0000005)equal to5, and what doestscsay about passing a number toparseInt? - What does the radix argument change, what happens with radix 1 or 37, and what does
parseIntassume without one? - Where do
Number()and unary+disagree, and why does+10nthrow whileNumber(10n)is10? - Which spellings does
Number()reject that a numeric literal accepts, such as"1_000"?
Examples it will need¶
-
parsing_numbers_compare_js.js— a table of inputs ("12px",""," 12 ","0x1f","0b101","1e3","1_000",null) throughparseInt,parseFloat,Number()and unary+ -
parsing_numbers_radix_js.js—parseIntwith radix 2, 16, 36, 1 and none, andparseInt(0.0000005)next toString(0.0000005) -
parsing_numbers_parseint_number_tserror.ts— tsc's TS2345 diagnostic for passing a number toparseInt
See also¶
- Converting on purpose —
Number()and unary+on values that are not strings map,filter,reduceand friends — why["1", "2", "3"].map(parseInt)goes wrongNaN,Infinityand-0— theNaNa failed parse returns, and how to test for it- BigInt —
BigInt("...")for integers past 2^53 - Higher-order functions — why passing parseInt straight to map goes wrong
- C: Parsing a number from text ↗ — the
atoi,sscanfandstrtolof C, which fail three different ways - Rust: Parsing out of a string ↗ — in Rust,
parsereturns aResultwhere JavaScript returnsNaN