-
Notifications
You must be signed in to change notification settings - Fork 0
/
isNumeric.ts
40 lines (38 loc) · 1.13 KB
/
isNumeric.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import type { Numeric } from './types/index.js';
import isBigInt from './isBigInt.js';
import isSymbol from './isSymbol.js';
/**
* Determines whether the given value is a number or a "numeric string".
*
* A string is considered numeric if it can be interpreted as / coerced to
* a number (as an integer or a float).
*
* @see https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion
*
* @example
* ```js
* isNumeric('11 23'); // false
* isNumeric('hey'); // false
* isNumeric(true); // false
* isNumeric(1); // true
* isNumeric(0); // true
* isNumeric(11.23); // true
* isNumeric('1'); // true
* isNumeric('0'); // true
* isNumeric('11.23'); // true
* ```
*/
export default function isNumeric(value: unknown): value is Numeric {
return !isSymbol(value) && !isBigInt(value) && !isNaN(_parseFloat(value)) && isFinite(value as number);
}
/*
* Passing in values like `Object.create(null)`
* causes `parseFloat` to throw `TypeError: Cannot convert object to primitive value`.
*/
function _parseFloat(value: unknown): number {
try {
return parseFloat(value as string);
} catch (error) {
return NaN;
}
}