Steve McLeod
Steve McLeod

Reputation: 52498

How do I check if a JavaScript parameter is a number?

I'm doing some trouble-shooting and want to add a check that a parameter to a function is a number. How do I do this?

Something like this...

function fn(id) {
    return // true iff id is a number else false
}

Even better is if I can check that the parameter is a number AND a valid integer.

Upvotes: 12

Views: 18540

Answers (6)

GaurabDahal
GaurabDahal

Reputation: 876

=== means strictly equals to and == checks if values are equal. that means "2"==2 is true but "2"===2 is false.

using regular expression

var intRegex = /^\d+$/;
if(intRegex.test(num1)) { 
//num1 is a valid integer
}

example of == vs. ===

Upvotes: 2

user187291
user187291

Reputation: 53960

i'd say

 n === parseInt(n)

is enough. note three '===' - it checks both type and value

Upvotes: 12

kei
kei

Reputation: 20521

function fn(id) {
    var x = /^(\+|-)?\d+$/;
    if (x.test(id)) {
        //integer
        return true;
    }
    else {
        //not an integer
        return false;
    }
}

Test fiddle: http://jsfiddle.net/xLYW7/

Upvotes: 0

thescientist
thescientist

Reputation: 2948

function fn(id){ 
  if((parseFloat(id) == parseInt(id)) && !isNaN(id)){
      return true;
  } else { 
      return false;
  } 
}

Upvotes: 0

Niklas
Niklas

Reputation: 30012

Check if the type is number, and whether it is an int using parseInt:

if (typeof id == "number" && id == parseInt(id))

Upvotes: 2

Daniel Cassidy
Daniel Cassidy

Reputation: 25657

function fn(id) {
    return typeof(id) === 'number';
}

To also check if it’s an integer:

function fn(id) {
    return typeof(id) === 'number' &&
            isFinite(id) &&
            Math.round(id) === id;
}

Upvotes: 24

Related Questions