Skip to content

Function: toNumber()

toNumber(value, options?): number | undefined

Coerce a loose numeric value to a real, FINITE number, or undefined when it carries no numeric meaning.

The one place a hand-typed number is interpreted, alongside toBoolean, toDate, and toDuration. Reach for it instead of Number(x) or a hand-rolled numeric regex: bare Number maps "", null, [], and whitespace to 0 and anything else to NaN, so a caller has to re-check the result every time, and ad hoc regexes tend to drift in what they accept.

Accepts: a finite number; a bigint; or a decimal string with an optional leading sign, leading/trailing whitespace, whitespace after the sign, digit-group separators ("1,000", "1 000"), a bare fraction (".5"), a trailing point ("1."), scientific notation ("1e3"), and an optional trailing percent sign ("25%", "1.5 %"). A trailing % divides the parsed value by 100, so "25%" becomes 0.25.

Separators are stripped without validating their placement, so "1,00,0" reads as 1000; this is a coercion for hand-typed configuration, not a locale-aware validator. Anything else, including NaN, Infinity, an empty or whitespace-only string, null, undefined, a boolean, multiple signs, malformed exponents, misplaced percent signs, or "12px", returns undefined.

Returns undefined rather than throwing, matching the other coercions, so it composes naturally with ?? fallbacks.

unknown

ToNumberOptions = {}

number | undefined

toNumber("1,000"); // 1000
toNumber(" -2.5 "); // -2.5
toNumber("1e3"); // 1000
toNumber("12.5 %"); // 0.125
toNumber(""); // undefined (Number("") would be 0)
toNumber("12px"); // undefined
toNumber("1 000", { separators: false }); // undefined