A Better Number() and Number.parseFloat()
const numberSafeParse = (input: string): number | null => {
if (input.trim() === "") return null;
let parsed = Number(input);
if (!Number.isFinite(parsed)) return null;
return parsed;
};
-
Returns
null
instead ofNaN
on failure (with matching type). -
Doesn’t parse things like “42foo” as
42
(vs usingNumber.parseFloat()
) -
Doesn’t parse whitespace-only things as
0
(vs usingNumber()
) -
Doesn’t parse “Nan” into
Nan
or “Infinity” intoInfinity
(vsNumber()
orNumber.parseFloat()
) -
Only parses token sequences that are exactly valid JS numbers