check is number js code example
Example 1: javascript check if number
//Updated dec 2020
// The first 2 Variations return a Boolean
// They just work the opposite way around
// IsInteger
if (Number.isInteger(val)) {
// It is indeed a number
}
// isNaN (is not a number)
if (isNaN(val)) {
// It is not a number
}
// Another option is typeof which return a string
if (typeof(val) === 'number') {
// Guess what, it's a bloody number!
}
Example 2: check if input is a number javascript
// Another option is typeof which return a string
if (typeof(val) === 'number') {
// Guess what, it's a bloody number!
}
Example 3: js check if string is number
isNaN(num) // returns true if the variable does NOT contain a valid number
isNaN(123) // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
Example 4: javascript check if variable is number
function isNumber(n) {
return !isNaN(parseFloat(n)) && !isNaN(n - 0);
}