normalizeNonNegativeNumber
Normalizes a value into a non‑negative finite number (zero or greater) or returns null when normalization is not possible. This helper accepts both native numbers and string representations of non‑negative numbers, ensuring predictable behavior without coercion surprises.
It never throws and never mutates input. Use it when you need a safe numeric normalization step before validation or further processing.
Signature
function normalizeNonNegativeNumber(value: unknown): number | null
| Name | Type | Description |
|---|---|---|
| value | unknown |
The value to normalize. |
Returns
One of:
- A number: If the input is a finite number greater than or equal to 0, or a string representing a valid non‑negative number.
null: If the input cannot be safely normalized (invalid type, invalid numeric form, negative,Infinite, orNaN).
Behavior
- Accepts:
- Finite numbers greater than or equal to zero.
- String representations of non‑negative numbers, such as
"0","3","3.14","0007","2.0". - Rejects:
- Negative numbers.
NaN,Infinity,-Infinity.- Empty strings or whitespace‑only strings
- Strings that are not simple numeric literals (e.g.,
"1e3","+5","-0","3.",".","3.14.15"). - Booleans, objects, arrays, symbols, functions, and all other non‑string, non‑number types.
- Trims string input before validation.
- Uses a strict numeric literal regex to avoid JavaScript coercion pitfalls.
- Never throws and never mutates input.
Examples
normalizeNonNegativeNumber(0)
// 0
normalizeNonNegativeNumber(3.14)
// 3.14
normalizeNonNegativeNumber("7")
// 7
normalizeNonNegativeNumber("003.50")
// 3.5
normalizeNonNegativeNumber(" 2.0 ")
// 2
normalizeNonNegativeNumber(-1)
// null
normalizeNonNegativeNumber("1e3")
// null (scientific notation not allowed)
normalizeNonNegativeNumber("+5")
// null (leading + not allowed)
normalizeNonNegativeNumber("3.")
// null (invalid numeric literal)
normalizeNonNegativeNumber(true)
// null
normalizeNonNegativeNumber({})
// null
Notes
- This helper is intentionally strict: it only accepts plain decimal literals to avoid coercion surprises and ambiguous numeric formats.
- Leading zeros are allowed (
"0007"→ 7), but signs (+or-) and exponent notation (eandE) are not. - Suitable for normalizing user input before validation of quantities, durations, sizes, pagination parameters, or any domain requiring a guaranteed non‑negative number.
- The function is pure and side‑effect‑free.