Skip to main content

parseIntDef()

parseIntDef(value, defaultValue?, radix?): number | null

Parses a string to an integer with a fallback default value.

note

Returns default for null, undefined, empty strings, and NaN results.


Parameters​

value: Nullish<string>​

The string value to parse (can be nullish or empty).

defaultValue?: Nullish<number> = null​

The value to return if parsing fails.

radix?: number​

The radix (base 2-36) for parsing.


Returns: number | null​

The parsed integer or default value.


See Also​

parseFloatDef


Since​

1.0.0


Example​

parseIntDef('42');            // => 42
parseIntDef('invalid'); // => null
parseIntDef('invalid', 0); // => 0
parseIntDef('1010', null, 2); // => 10 (binary)
parseIntDef('FF', null, 16); // => 255 (hex)

How it works?​

Parses a string to an integer with a fallback default value, supporting custom radix.

Validation Flow​

Common Inputs​

ValueDefaultRadixResult
'42'null-42
'invalid'0-0
'1010'null210
'FF'null16255
null0-0

Use Cases​

Parse integers safely πŸ“Œβ€‹

Convert strings to integers with nullish handling and default values. Essential for pagination (page numbers, limits) and ID handling.

const page = parseIntDef(params.page, 1);
const limit = parseIntDef(params.limit, 20);

Specify radix explicitly​

Parse binary, octal, or hexadecimal strings safely. Useful for low-level data processing or color parsing.

const flags = parseIntDef("1010", 0, 2); // Binary to decimal: 10
const color = parseIntDef("FF", 0, 16); // Hex to decimal: 255