How to Write isNumber() in Javascript? [Duplicate]

My guess would be:

function isNumber(val) {
    return val === +val;
}

Is there a better way?

Previous Reference

Validate decimal numbers in JavaScript - IsNumeric()

8
var isNumber = function isNumber(value) 
{
   return typeof value === 'number' && isFinite(value);
}

This code above is taken from the book "JavaScript - the good parts".

/* ANSWER UPDATE BEGIN - in reply to some comments
below from the person who asked the question and others */

var isNumber = function isNumber(value) {
  return typeof value === 'number' && isFinite(value);
}

var isNumberObject = function isNumberObject(n) {
  return (Object.prototype.toString.apply(n) === '[object Number]');
}

var isCustomNumber = function isCustomNumber(n){
  return isNumber(n) || isNumberObject(n);
}

console.log(isCustomNumber(new Number(5)));
console.log(isCustomNumber(new Number(5.2)));
console.log(isCustomNumber(new Number(5.5)));
console.log(isCustomNumber(new Number(-1)));
console.log(isCustomNumber(new Number(-1.5)));
console.log(isCustomNumber(new Number(-0.0)));
console.log(isCustomNumber(new Number(0.0)));
console.log(isCustomNumber(new Number(0)));
console.log(isCustomNumber(new Number(1e5)));

console.log(isCustomNumber(5));
console.log(isCustomNumber(5.2));
console.log(isCustomNumber(5.5));
console.log(isCustomNumber(-1));
console.log(isCustomNumber(-1.5));
console.log(isCustomNumber(-0.0));
console.log(isCustomNumber(0.0));
console.log(isCustomNumber(0));
console.log(isCustomNumber(1e5));

/* ANSWER UPDATE END - in reply to some comments
below from the person who asked the question and others */

12

If you do not want to include strings, and you do want to include Infinity, you can compare the Number coercion of the argument to the argument:

function isNumber(n){
    return Number(n)=== n;
}

//test

[0, 1, 2, -1, 1.345e+17, Infinity, false, true, NaN, '1', '0'].map(function(itm){
    return itm+'= '+isNumber(itm);
});

// returned values
0= true
1= true
2= true
-1= true
134500000000000000= true
Infinity= true
false= false
true= false
NaN= false
'1'= false
'0'= false
1
function isNumber(val){
    return typeof val==='number';
}
2

If you want "23" to be a number, then

function isNumber(val) {
    return !isNaN(val);
}
2
function isNumber(val) {
        // negative or positive
        return /^[-]?\d+$/.test(val);
    }
3

I like this solution:

function isNumber(val) {
    return (val >=0 || val < 0);
}
3
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest