Skip to content

safeAnyToNumber

Safely convert any value to a number.

Type definition

function safeAnyToNumber<T = unknown>(
inputVal: Exclude<T, (...args: never) => unknown>,
fallbackNum?: number,
) {
result: number
success: boolean
}
[] => {result: 0, success: true} // same result with inputVal = [null] or [undefined]
[12] => {result: 12, success: true}
['12'] => {result: 12, success: true}
['12', '13'] => {result: fallbackNum, success: false}
'[12]' => {result: fallbackNum, success: false}
[true] => {result: fallbackNum, success: false} // same result with inputVal = [false]
[BigInt(9007199254740991)] => {result: 9007199254740991, success: true}
[BigInt(9007199254740991000000)] => {result: 9.007199254740991e+21, success: true}
['BigInt(9007199254740991)'] => {result: fallbackNum, success: false}
'[BigInt(9007199254740991)]' => {result: fallbackNum, success: false}

Fallback

Default fallback number is 0.

Example

Convert string to number:

Try typing any string (eg: 123.e5, 0b1010, a123) in the input field below.