Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 624
Pradyot Avatar asked Nov 13 '13 21:11

Pradyot


People also ask

How do you check if a decimal is an integer in Python?

Check if float is integer: is_integer() float has is_integer() method that returns True if the value is an integer, and False otherwise.

How do you check if a number is an integer Python?

To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.

How do you check if a number is integer or float in Python?

Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int): . The isinstance function will return True if the passed in object is an instance of the provided class ( int or float ).

How do you test if a number is an integer?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .


1 Answers

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

>>> from decimal import Decimal >>> Decimal('3.14') % 1 == 0 False >>> Decimal('3') % 1 == 0 True >>> Decimal('3.0') % 1 == 0 True 
like image 124
poke Avatar answered Sep 29 '22 10:09

poke