Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that variable is a number

How can I check that a variable is a number, either an integer or a string digit?

In PHP I could do:

if (is_int($var)) {     echo '$var is integer'; } 

Or:

if (is_numeric($var)) {     echo '$var is numeric'; } 

How can I do it in jQuery/JavaScript?

like image 611
Richard Knop Avatar asked Aug 29 '09 22:08

Richard Knop


People also ask

How do you say if a variable is a number in Python?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values.

How do you check if a variable is an integer?

Using int() function The function int(x) converts the argument x to an integer. If x is already an integer or a float with integral value, then the expression int(x) == x will hold true. That's all about determining whether a variable is an integer or not in Python.

How do you verify a variable?

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.


2 Answers

The javascript function isNaN(variable) should do the trick. It returns true if the data is not a number.

like image 165
AAA Avatar answered Sep 28 '22 11:09

AAA


I'd go with

isFinite(String(foo)) 

See this answer for an explanation why. If you only want to accept integer values, look here.

like image 32
Christoph Avatar answered Sep 28 '22 11:09

Christoph