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?
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.
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.
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.
The javascript function isNaN(variable)
should do the trick. It returns true if the data is not a number.
I'd go with
isFinite(String(foo))
See this answer for an explanation why. If you only want to accept integer values, look here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With