Checking whether a variable is an integer or not
If you need to do this, do
isinstance(<var>, int)
unless you are in Python 2.x in which case you want
isinstance(<var>, (int, long))
Do not use type
. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int
, your new class should register as an int
, which type
will not do:
class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an int
, instead of mandating that it be one.
BUT
The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x
is an integer; assume that it is and catch the exception results if it isn't:
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.
How to check if a variable is an integer or a string?
In my opinion you have two options:
Just try to convert it to an
int
, but catch the exception:try:
value = int(value)
except ValueError:
pass # it was a string, not an int.This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit()
returnsTrue
only if all characters in the string are digits (0
-9
).The
unicode
/ Python 3str
type equivalent isunicode.isdecimal()
/str.isdecimal()
; only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int()
values, as whitespace and +
and -
are also allowed in int()
values. The first form will happily accept ' +10 '
as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
How to check if a variable is an integer in JavaScript?
Use the === operator (strict equality) as below,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
Checking if a variable is an integer
You can use the is_a?
method
>> 1.is_a? Integer
=> true
>> "dadadad@asdasd.net".is_a? Integer
=> false
>> nil.is_a? Integer
=> false
How to Check Whether a Variable is an Integer or Not
If you divide an integer by another integer you will always have an integer.
You need the modulo (remainder) operation
int num1 = 15;
int num2 = 16;
int num3 = 5;
System.out.println("num1/num3 = "+num1/num3);
System.out.println("num2/num3 = "+num2/num3);
System.out.println("num1%num3 = "+num1%num3);
System.out.println("num2%num3 = "+num2%num3);
If the modulo is not 0 then the result would not be an integer.
How can I check if a value is of type Integer?
If input value can be in numeric form other than integer , check by
if (x == (int)x)
{
// Number is integer
}
If string value is being passed , use Integer.parseInt(string_var).
Please ensure error handling using try catch in case conversion fails.
How do I test whether a variable is an integer value in python?
You can test arg2 type this way:
if (type(arg2) != int):
arg2=0
How to check if a variable is an integer?
Rather than using sets you could just do a simple range test, e.g.
IF (s[i] < '0') OR (s[i] > '9') THEN
...
Related Topics
Shell Out from Ruby While Setting an Environment Variable
Ruby: Why Does Puts Call To_Ary
Set Utf-8 as Default for Ruby 1.9.3
How to Say Something Happened "X Minutes Ago" or "X Hours Ago" or "X Days Ago" in Ruby
Ruby SQLite3 Installation SQLite3_Libversion_Number() MACos Sierra
Peer-To-Peer File Sharing with Web Sockets
Activerecord::Adapternotspecified Database Configuration Does Not Specify Adapter
How to Check a Word Is Already All Uppercase
How to Make Part of a Regular Expression Optional in Ruby
Split String into a List, But Keeping the Split Pattern
Generate a Powerset of a Set Without Keeping a Stack in Erlang or Ruby
Differencebetween <%= ... %> and <% ... %> in Ruby on Rails
Ruby on Rails Rmagick on Windows 7
Why Does Code Need to Be Reloaded in Rails 3
How to Serve Requests Concurrently with Rails 4