Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write isNumber() in JavaScript? [duplicate]

Tags:

javascript

My guess would be:

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

Is there a better way?

Previous Reference

Validate decimal numbers in JavaScript - IsNumeric()

like image 867
nativist.bill.cutting Avatar asked Nov 23 '13 23:11

nativist.bill.cutting


5 Answers

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 */

like image 177
peter.petrov Avatar answered Oct 19 '22 02:10

peter.petrov


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
like image 22
kennebec Avatar answered Oct 19 '22 03:10

kennebec


function isNumber(val){
    return typeof val==='number';
}
like image 25
markasoftware Avatar answered Oct 19 '22 01:10

markasoftware


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

function isNumber(val) {
    return !isNaN(val);
}
like image 7
Ari Porad Avatar answered Oct 19 '22 01:10

Ari Porad


function isNumber(val) {
        // negative or positive
        return /^[-]?\d+$/.test(val);
    }
like image 4
davs Avatar answered Oct 19 '22 01:10

davs