How to check if a number is an integer in python?
In mathematics, integers are the number that can be positive, negative, or zero but cannot be a fraction. For example, 3, 78, 123, 0, -65 are all integer values. Some floating-point values for eg. 12.00, 1.0, -21.0 also represent an integer. This article discusses various approaches to check if a number is an integer in python.
Check if a number is an integer using the type() function
In Python, we have a built-in method called type() that helps us to figure out the type of the variable used in the program. The syntax for type() function is given below.
Please enable JavaScript
In the following example, we declare a function check_integer to check if a number num is an integer value or not. The program checks if the type(num) is equal to the int datatype. If the condition returns True if block is executed. Otherwise, else block is executed.
The above code returns the output as
Check if a number is an integer using the isinstance() function
The isinstance() method is an inbuilt function in python that returns True if a specified object is of the specified type. Otherwise, False. The syntax for instance() function is given below.
In the following example, we declare a function check_integer to check if a number num is an integer value or not. The program checks if the num is of int data type using the isinstance(num, int) function. If the condition is True if block is executed, Otherwise else block is executed.
The above code returns the output as
The number such as 12.0, -134.00 are floating-point values, but also represent an integer. If these values are passed as an argument to the type() or isinstance() function, we get output as False.
Checking if a floating-point value is an integer using is_integer() function
In python, the is_integer() function returns True if the float instance is a finite integral value. Otherwise, the is_integer() function returns False. The syntax for is_integer() function is given below.
In the following example, we declare a function check_integer to check if a floating-point number f is an integer value or not. If the f.is_integer() function evaluates to True, if block is executed. Otherwise, else block is executed.
The above code returns the output as
Checking if a floating-point value is an integer using split() + replace()
In the following example, we declare a function check_integer to check if a number num is an integer value or not. The program checks if the type(int) is equal to the integer data type. If the condition is True if block is executed.
If the condition is False, the number is a floating-point value, and hence else block is executed. In the else block, we check if the float instance is a finite integral value. Consider a number num = 12.0. The number num also represents an integer.
We convert the number num to string data type using str() function and store it in the variable str_num = ‘12.0’. The string str_num is splitted from decimal point and is assigned to the variable list_1 = [’12’, ‘0’]. The element at position 1 of list_1 gives the decimal part of the number and is stored in variable ele.
We replace every ‘0’ character in the string ele with a blank space and assign the result to variable str_1. If the length of the str_1 is 0, then the floating instance is also an integer.
Проверьте, является ли переменная целым числом или нет в Python
В этом посте мы обсудим, как проверить, является ли переменная целым числом или нет в Python.
1. Использование isinstance() функция
Стандартное решение для проверки, является ли данная переменная целым числом или нет, использует isinstance() функция. Он возвращается True если первый аргумент является экземпляром второго аргумента.
Вы также можете использовать числовые абстрактные базовые классы вместо конкретных классов. Чтобы проверить целочисленное значение, вы можете использовать numbers.Integral Класс Python:
2. Использование float.is_integer() функция
Если вам нужно рассмотреть числа с плавающей запятой со всеми нулями после запятой, рассмотрите возможность использования float.is_integer() функция. Он возвращается True если экземпляр с плавающей запятой конечен с целым значением и False в противном случае.
3. Использование int() функция
Наконец, вы можете использовать конструктор int для проверки целочисленных значений. Функция int(x) преобразует аргумент x до целого числа. Если x уже является целым числом или числом с плавающей запятой с целым значением, то выражение int(x) == x будет соответствовать действительности.
How to check if a float value is a whole number
I am trying to find the largest cube root that is a whole number, that is less than 12,000.
I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?
![]()
15 Answers 15
To check if a float value is a whole number, use the float.is_integer() method:
The method was added to the float type in Python 2.6.
Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
You’d have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000 :
If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
Python-сообщество
Здравствуйте. С Python познакомился только вчера, возникло много вопросов, большинство нахожу на форумах, а вот с этим не смог справиться сам.
Пример: выводятся подобные большие числа:
#2 Ноя. 24, 2013 08:48:28
Определить целое число или нет
Отредактировано Tort (Ноя. 24, 2013 08:55:27)
#3 Ноя. 24, 2013 08:57:12
Определить целое число или нет
#4 Ноя. 24, 2013 08:57:39
Определить целое число или нет
define “целое число”
из примера последние четыре можно назвать целыми
#5 Ноя. 24, 2013 09:11:05
Определить целое число или нет
Это преобразование в целое ведь? Мне нужно именно отобрать целое число
smoke853
Спасибо, похоже это то, что я и искал 
sergeek
Да, вы правы. Мне другие не нужны, так что после вывода первого такого числа сделаю break
#6 Ноя. 24, 2013 12:06:46
Определить целое число или нет
#7 Ноя. 24, 2013 15:36:49
Определить целое число или нет
Влезу я и сюда, со своей функциональщиной, может пригодится:
`map` здесь не нужен, если есть уверенность, что все элементы списка, это <float>.