d
Amit DhamuSoftware Engineer
 

is_numeric

2 minute read 00000 views

PHP provides an in-built function to determine if a variable is a number or a numeric string.

We can do something similar in Javascript.

const isNumeric = value =>
  !Number.isNaN(Number(value)) && !['object', 'boolean'].includes(typeof value)

Output

isNumeric('3')          // ✅ true
isNumeric(3)            // ✅ true
isNumeric(0)            // ✅ true
isNumeric('0')          // ✅ true
isNumeric('1.5')        // ✅ true
isNumeric(15_000)       // ✅ true
isNumeric(15,000)       // ✅ true
isNumeric('15,000')     // ✅ true
isNumeric('foo')        // ❌ false
isNumeric('123abc')     // ❌ false
isNumeric({})           // ❌ false
isNumeric([])           // ❌ false
isNumeric(true)         // ❌ false
isNumeric(false)        // ❌ false
isNumeric(() => 123)    // ❌ false
isNumeric(() => '123')  // ❌ false
isNumeric(() => 'abc')  // ❌ false
isNumeric(NaN)          // ❌ false