21

I would like to determine if a numeric value in Python is a whole number. For example, given:

y = x / 3

I want to distinguish between values of x which are evenly divisible by 3 those which are not.

Ron Zhang
  • 195
  • 1
  • 3
  • 17
johntheripper
  • 271
  • 2
  • 3
  • 8
  • 6
    What do you mean by decimals in this case? An integer is an integer. It is always a whole number. Somehow it sounds like you want to check an integer for diseases: *This integer has decimals, we have to bring it to the hospital!* ;) – Felix Kling Jun 04 '11 at 23:18
  • 2
    What do you mean by "decimals" in this context? Decimal point? Integers never have them (a number with a decimal point is parsed as a floating-point number). – C. K. Young Jun 04 '11 at 23:19
  • 2
    An integer by definition has no decimals. Tada! You are done! – Winston Ewert Jun 04 '11 at 23:20
  • I understand that by “integer” he means “number”, and by “decimals” he means “fractional part”, so I believe interjay's answer is spot on. – tzot Jun 05 '11 at 00:21
  • The accepted answer does not answer the title. I came here through google trying to answer the title question. Since the poster has accepted an answer which differs from the title, can/should we edit the title? See [related meta post](http://meta.stackoverflow.com/questions/272663/how-to-deal-with-questions-whose-title-description-and-accepted-answer-dont-m). NOTE: If the title is fixed this becomes a duplicate question of [this](http://stackoverflow.com/questions/8002217/how-do-you-check-whether-a-number-is-divisible-by-another-number-python). – AnnanFay May 15 '16 at 20:22

9 Answers9

70

Integers have no decimals. If you meant "check if a number got decimals in Python", you can do:

not float(your_number).is_integer()
Artur Gaspar
  • 4,407
  • 1
  • 26
  • 28
28
if x % 3 == 0:
    print 'x is divisible by 3'
interjay
  • 107,303
  • 21
  • 270
  • 254
  • 3
    @lev Part of answering questions here is understanding what the OP actually meant to ask. Read more than just the title of the question. Here it's clear that the OP wanted to know how to tell if one number is divisible by another. Doing that by checking if the result of division is an integer is unpythonic and error-prone. – interjay May 10 '16 at 11:44
  • 1
    Important: this does not check if a number is a decimal, as the title and part of the question would suggest to be asking for. For example, if you have x == 0.3, the code above will print 'x is divisible by 3', but x is not a whole number. See Artur Gaspar answer for checking if a number is a decimal. @interjay this should do. – lev May 10 '16 at 12:59
  • There is only one problem with the code at the moment. In Python, you are supposed to put parentheses around the stuff you are going to print. So the print bit of code should be `print ('x is divisible by 3')`. If not, you will still get an error. – Ron Zhang Sep 19 '18 at 21:39
  • It appears that the asking user didn't initially specify the version he/she is using, nor does it appear in the question's comments about discussion relating to Python 2 or 3. I had made a suggested edit about adding category Python 2 for clarification. – Ron Zhang Sep 20 '18 at 06:16
  • This completely-irrelevant-to-anyone-besides-the-original-asker accepted answer really demonstrates what I hate about the concept of accepted answers. – Boris Verkhovskiy Nov 22 '19 at 12:14
  • 1
    @Boris The asker wanted to know how to tell if a number is divisible by another. This answer is relevant to anyone with the same question. The fact that the title of the question asks something different is an instance of an [XY problem](https://en.wikipedia.org/wiki/XY_problem). Literally answering that question would be counterproductive due to floating-point inaccuracies. In fact, using the other answer's `float(your_number).is_integer()` to determine divisibility would lead to incorrect results in many cases. Please read the entire question before criticizing answers, not just the title. – interjay Nov 22 '19 at 12:51
4

Edit: As Ollie pointed out in the comment below this post, is_integer is part of the standard library and should therefore not be reimplemented as I did below.

This function uses the fact that every other whole number will have at least one number divisible by two with no remainder. Any non-zero fractional representation in either n or n+1 will cause both n%2 and (n+1)%2 to have a remainder. This has the benefit that whole numbers represented as float values will return True. The function works correctly for positive and negative numbers and zero as far as I can determine. As mentioned in the function, it fails for values very close to an integer.

def isInteger(n):
    """Return True if argument is a whole number, False if argument has a fractional part.

    Note that for values very close to an integer, this test breaks. During
    superficial testing the closest value to zero that evaluated correctly
    was 9.88131291682e-324. When dividing this number by 10, Python 2.7.1 evaluated
    the result to zero"""

    if n%2 == 0 or (n+1)%2 == 0:
        return True
    return False
  • 2
    As answered earlier (http://stackoverflow.com/a/6239987/592174), is_integer is part of Python standard library. http://docs.python.org/library/stdtypes.html#float.is_integer You shouldn't reimplement it. – Olli Apr 10 '12 at 15:13
3

Here's another method:

x = 1/3  # insert your number here
print((x - int(x)) == 0)  # True if x is a whole number, False if it has decimals.

This works because int(x) essentially takes the floor of the number (ex. 3.6453 -> 3). If there's something left over once you subtract the floor, it can't have been a whole number.

Sakeeb Hossain
  • 662
  • 5
  • 19
2

x % 3 == 0 will be True if x / 3 is an integer.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

convert 1.0 => 1 & convert 1.x => 1.x

This code if float numbers has decimal part like 1.5 will return 1.5 & if it is 35.00 it return 35:

a = ReadFrom()    
if float(a).is_integer(): # it is an integer number like 23.00 so return 23
       return int(a)
 else: # for numbers with decimal part like : 1.5 return 1.5
       return float(a)
Hamed Jaliliani
  • 2,789
  • 24
  • 31
1

assuming you mean if a string containing digits also has a decimal point:

Python 2.6.6 (r266:84292, Apr 20 2011, 11:58:30) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> number='123.4'
>>> '.' in number
True
>>> number='123'
>>> '.' in number
False
>>>

To test if it's integral you could mod 1:

>>> 1.0/3 % 1
0.33333333333333331
>>> 1/3 % 1
0
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
1

In Python 2, dividing an int by an int returns an int (unless python was invoked with the -Qnew option, or a from __future__ import division is at the beginning of the source; in that case / returns a float); a // specifies integer division.

In Python 3, dividing an int by an int returns a float if you use "/", or an int if you use "//".

If you want to know whether an int will divide into another int exactly, use "%" to look for a remainder.

tzot
  • 92,761
  • 29
  • 141
  • 204
MRAB
  • 20,356
  • 6
  • 40
  • 33
-3

It is best to make your determination before doing the division, assuming that your x variable is an integer.

Trying to do equality tests or comparisons on floating point numbers is dangerous: http://www.lahey.com/float.htm

The answer already provided using modulus before doing the division to see if one integer is divsible by the other integer is safe. After you do a division and are dealing with possibly floating point values, then numbers are no longer exactly integers or not.

Ivan Novick
  • 745
  • 2
  • 8
  • 12