Skip to main content
@spa-tools/utilities

ensureNum()

The ensureNum<F>() function checks if the given value is a valid number or can be parsed to a valid number and if so returns number; otherwise returns fallback value.

The generic F type is used to define the type of the fallback value.

Usage

import { ensureNum } from '@spa-tools/utilities';

const validNum = ensureNum('123', 0);
console.log(validNum);
// --> 123

const invalidNum = ensureNum('abc', -1);
console.log(invalidNum);
// --> -1

Arguments

NameTypeDescription
valueunknownThe value to parse as number
fallbackFThe value that will be returned if value cannot be parsed an a number

Returns

Returns parsed number or the fallback value of type F.