isNumeric
Checks if a value is a finite number or a numeric string.
1/**
2 * Checks if a value is a finite number or a numeric string.
3 *
4 * @param value - The value to check.
5 * @returns True if the value is numeric, false otherwise.
6 */
7export function isNumeric(value: any): boolean {
8 return (
9 (typeof value === 'number' && isFinite(value)) ||
10 (typeof value === 'string' && value.trim() !== '' && !isNaN(Number(value)))
11 );
12}
Supports Both Numbers and Numeric Strings
Handles common input types like
42
and'42.5'
, improving flexibility in mixed-type environments.Robust Whitespace Handling
Trims string inputs before evaluation to avoid false negatives due to leading/trailing spaces.
Safe Against NaN and Infinities
Explicitly filters out
NaN
,Infinity
, and-Infinity
, ensuring only valid finite numbers pass.Practical and Lightweight
Simple logic covers a broad range of real-world cases without relying on regex or external libraries.
Tests | Examples
1test('isNumeric - with valid numbers', () => {
2 expect(isNumeric(42)).toBe(true);
3 expect(isNumeric(-3.14)).toBe(true);
4 expect(isNumeric('5')).toBe(true);
5 expect(isNumeric(' 7.5 ')).toBe(true);
6});
7
8test('isNumeric - with invalid values', () => {
9 expect(isNumeric(NaN)).toBe(false);
10 expect(isNumeric(Infinity)).toBe(false);
11 expect(isNumeric(undefined)).toBe(false);
12 expect(isNumeric(null)).toBe(false);
13 expect(isNumeric('')).toBe(false);
14 expect(isNumeric('abc')).toBe(false);
15 expect(isNumeric([])).toBe(false);
16 expect(isNumeric({})).toBe(false);
17});
Common Use Cases
User Input Validation
Check if form inputs or query parameters can be safely parsed as numbers.
Data Parsing from CSV/JSON
Identify numeric fields when reading values from loosely typed data sources.
Sanity Checks in Dynamic Code
Prevent runtime errors by verifying values before performing numeric operations.
Filtering and Cleanup
Remove or flag non-numeric values from datasets, especially when imported from untrusted sources.
Conditional Type Coercion
Safely convert values to numbers only when appropriate, avoiding
NaN
pollution.