python Decimal - checking if integer

I am using the Decimal library in Python, and printing out the values using format(value, 'f'), where value is a Decimal. I get numbers in the form 10.00000, which reflects the precision on the decimal. I know that float supports is_integer, but there seems to be a lack of a similar API for decimals. I was wondering if there was a way around this.

You could use the modulo operation to check if there is a non-integer remainder:

>>> from decimal import Decimal
>>> Decimal('3.14') % 1 == 0
>>> Decimal('3') % 1 == 0
>>> Decimal('3.0') % 1 == 0

python Decimal - checking if integer, To check if a float value is a whole number, use the float.is_integer() method: > Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating 0: print("We have a decimal number here!"). How to check (determine) whether a number is integer or decimal in Python is explained with sample code in the following cases. Check if object is int or float: isinstance() Check if float is integer: is_integer() Check if numeric string is integer; If you want to get velues of the fractional and integer parts, see the following post.

Try math.floor(val) == val or val == int(val).

How to check if a float value is a whole number, Checking if a number is an integer or float evaluates to True or False . For instance, checking if 25.9 is of type float and int evaluates to True and False� fraction = 0.001 decimal_places = int(f'{fraction:e}'.split('e')[-1]) This makes use of the scientific notation (m x 10^n), which already provides the number of decimal places in form of the power (n) of 10, to which the coefficient (m) is raised, ie. -3, derived from 1.000000e-03 for the above example.

The mathematical solution is to convert your decimal number to integer and then test its equality with your number.

Since Decimal can have an arbitrary precision, you should not convert it to int or float.

Fortunately, the Decimalclass has a to_integral_value which make the conversion for you. You can adopt a solution like this:

def is_integer(d):
    return d == d.to_integral_value()


from decimal import Decimal

d_int = Decimal(3)
assert is_integer(d_int)

d_float = Decimal(3.1415)
assert not is_integer(d_float)


How to check if a number is an int or float in Python, The decimal module provides support for decimal floating point arithmetic. Construction from an integer or a float performs an exact conversion of the Decimals interact well with much of the rest of Python. The purpose of the context argument is determining what to do if value is a malformed string. if number >= 10000 and number >= 30000: print ("you have to pay 5% taxes") actually checks if number is larger than both 10000 and 30000. Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison: if 10000 <= number <= 30000: print ("you have to pay 5% taxes")

Decimal does have a "hidden" method called _isinteger() that works kind of the like the float's is_integer() method:

>>> Decimal(1)._isinteger()
>>> Decimal(1.1)._isinteger()
Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 4.1\src\debug\tserver\", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "C:\Python26\Lib\", line 649, in __new__
    "First convert the float to a string")

As you can see, you would have to catch an exception though. Alternatively, you could do the test on the value BEFORE you pass it to Decimal using the float's method as you mentioned or by using isinstance.

9.4. decimal — Decimal fixed point and floating point arithmetic , Get code examples like "check if number is integer python" instantly right from your google search results with the Grepper Chrome Extension. 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. share.

You can call as_tuple() on a Decimal object to get the sign, the sequence of digits, and the exponent which together define the Decimal value.

If the exponent of a normalized Decimal is non-negative, then your value doesn't have a fractional component, i.e., it is an integer. So you can check for this very easily:

def is_integer(dec):
    """True if the given Decimal value is an integer, False otherwise."""
    return dec.normalize().as_tuple()[2] >= 0

Try it and see:

from decimal import Decimal

decimals = [

for d in decimals:
    print("Is {} an integer? {}".format(d, is_integer(d)))
Is 0 an integer? True
Is 0.0000 an integer? True
Is 1 an integer? True
Is -1 an integer? True
Is 1000000 an integer? True
Is 0.1 an integer? False
Is -9E-10 an integer? False
Is 32.4 an integer? False

check if number is integer python Code Example, How to check (determine) whether a number is integer or decimal in Python is explained with sample code in the following cases. Check if object is int or float:� In most of your Python programs you will want to interact with the end-user by asking questions and retrieving user inputs. To do so you can use the input() function: e.g. Sometimes you will need to retrieve numbers. Whole numbers (numbers with no decimal place) are called integers. To use them as integers you will need to convert the user input into an integer using the int() function. e.g

How to check if float can be exactly represented as an integer, For example, the following code checks if an object is an integer: Python's decimal module can be used to define higher (or lower) precision numbers than� First check if it's an int (or a long), then check if it's a float and, if it is, check if is_integer() is true. Notice that there is no long type in Python 3. – Agostino Apr 29 '15 at 18:44

Basic Object Types — Python Like You Mean It, is_int — Find whether the type of a variable is integer To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use first number must be 1 thru 9, followed by a number 0-9, no decimals Python input() function always convert the user input into a string. but how to check user input is a number. We can Convert string input to int or float type to check string input is an integer type. also using isdigit() method of string class we can check input string is number or string.

is_int - Manual, For instance, 5 is an integer whereas 5.0 is a floating-point number. a value belongs to and isinstance() function to check if it belongs to a particular class. The numbers we deal with every day are of the decimal (base 10) number system . In python, I import a file that has different length decimal places in the numbers, such as 7.2 or 7.2332 Is it possible to find out the number of decimal places in the number, if so, how? All the question I can find on SO are about formatting to a specific decimal place, but thats not what I am doing.

  • this method does not work if a value is too big, it gives you decimal.InvalidOperation: quotient too large in //, % or divmod
  • how large is too large? somewhere over 10^20 ref: DivisionImpossible for very large numbers
  • The int suggestion is good. math.floor is a poor choice because it relies on floats, which cannot accurately represent Decimals. And you even have to import a module just to get this inaccurate result.
  • Yeah, now that I think about it the math version isn't the best idea. I'd just finished writing some math-intensive JavaScript when I wrote the answer, so the js Math object was still stuck in my brain.
  • Using int(val) successfully.
  • Converting Decimal value to integer is right... but why can't you use int? Python transparently uses arbitrary-precision integers as necessary.
  • Yes, you can convert to arbritrary-precision integer, but I'm not sure it is more efficient than using to_integral_value().
  • You didn't mention anything about efficiency. You said int wouldn't be able to handle it. Until it's shown that int is too slow of a solution, there is no reason to bring up something more complicated.
  • Incidentally, on my machine, int is faster than to_integral_value.
  • Now the only issue i see , is_integer does not seem to work as i would expect. This might have to do with float representation. Conside this: num1 = 0.00002
  • Yeah, I get a traceback about needing to convert the float into a string if I do that. Not sure why that's implemented that way.
  • As of Python 2.7, Decimal instances can be constructed directly from floats.
  • The leading underscore means it's a private method so I don't think using it outside would be considered pythonic...
  • Python 3.6: AttributeError: 'decimal.Decimal' object has no attribute '_isinteger'