CKTIS / JavaScript
Number.parseInt: parsing an integer prefix
Number.parseInt converts its argument to text and returns the integer from the longest valid prefix in the selected radix, or NaN.
Version: ECMAScript 2015 onward; example target: Node.js 24.22.2
Syntax
Number.parseInt(string, radix)Number.parseInt(value, radix) first applies ToString, removes leading white space, and recognizes an optional + or -. The radix undergoes ToInt32: after conversion, 0 selects the default, 2..36 is valid, and any other value produces NaN. Parsing stops before the first digit invalid for that radix, so "15px" in radix 10 yields 15 rather than an error.
With the default radix, 10 is used except that a 0x/0X prefix selects 16. The 0b and 0o prefixes are not recognized here; an explicit radix is safer for input data. If no valid digit is consumed, the result is NaN; a -0 result keeps its sign. A very large mathematical integer is returned as a Number and can be rounded.
Number.parseInt has existed since ECMAScript 2015, is the same function as global parseInt, and is not a constructor. A BigInt is first converted to text and can lose precision; a Symbol throws TypeError, while objects supplied as the value or radix can run conversion code and propagate its exception. To require a full match, validate the entire text first.
Examples
console.log(Number.parseInt("42", 10), Number.parseInt("0x10", 16), Number.parseInt("101", 2));
console.log(Number.parseInt("15px", 10), Number.parseInt("bad", 10));
console.log(Number.parseInt("0x10"), Number.parseInt("0x10", 10));
console.log(Object.is(Number.parseInt("-0", 10), -0), Number.parseInt === parseInt);
console.log(Number.parseInt("10", 1), Number.parseInt("10", 37));
try { Number.parseInt(Symbol("x"), 10); } catch (error) { console.log(error instanceof TypeError); }Result
42 16 5 15 NaN 16 0 true true NaN NaN true
Number.parseInt → explicit radices, the 0x prefix, NaN, and signed -0