Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 690
Steve McLeod Avatar asked Jun 22 '11 14:06

Steve McLeod


People also ask

How do you check if a character is a number in JavaScript?

To check if a character is a number, pass the character as a parameter to the isNaN() function. The function checks if the provided value is NaN (not a number). If the function returns false , then the character is a valid number. Copied!

How do you check if a JavaScript string is a number?

Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.

How do you know if an input is Not-a-Number in JavaScript?

isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.


3 Answers

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;
}
like image 70
Daniel Cassidy Avatar answered Sep 23 '22 22:09

Daniel Cassidy


i'd say

 n === parseInt(n)

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

like image 44
user187291 Avatar answered Sep 22 '22 22:09

user187291


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

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

like image 23
Niklas Avatar answered Sep 23 '22 22:09

Niklas