Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable contains a numerical value in Javascript?

Tags:

javascript

In PHP, it's pretty easy:

is_numeric(23);//true
is_numeric("23");//true
is_numeric(23.5);//true
is_numeric(true);//false

But how do I do this in Javascript? I could use a regular expression, but is there a function for this?

like image 325
Vordreller Avatar asked Mar 01 '09 23:03

Vordreller


People also ask

How do you check if a value is numeric or not?

isNumeric() method to check whether a value is numeric or a number. The $. isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers, otherwise it returns false .

How do you check if a value 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.

How do you check if a variable contains a value?

Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

How do you check if a string contains any number in JavaScript?

Use the RegExp. test() method to check if a string contains at least one number, e.g. /\d/. test(str) . The test method will return true if the string contains at least one number, otherwise false will be returned.


2 Answers

This checks for numerical values, including negative and floating point numbers.

function is_numeric(val){
    return val && /^-?\d+(\.\d+)?$/.test(val + '');
}

@Vordreller: I corrected the Regex. It should work properly now.

like image 131
Manu Avatar answered Sep 28 '22 08:09

Manu


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

That should do the trick.

like image 44
Aistina Avatar answered Sep 28 '22 10:09

Aistina