i'm making a program which divides a lot of numbers and I want to check if the number gets decimals or not. I also want it to print those decimals. Example:
foo = 7/3
if foo has a 3 in the decimals: # (Just an example of what I want to do there)
print("It works!")
elif foo has no decimals: # (another example)
print("It has no decimals")
EDIT: Ok, so since "check which decimal is afterwards" brought some confusion, let me explain. I want to be able to check IF a number has decimals. For example, 7/3 (foo) gives me decimals, but I want python to tell me that without me having to do the math. forget the "which decimal" part
If you just want to test whether a division has decimals, just check the modulo:
foo = a % b
if foo != 0:
# Then foo contains decimals
pass
if foo == 0:
# Then foo does NOT contain decimals
pass
However (since your question is a bit unclear) if you want to split the integer and decimal parts then use math.modf() function:
import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)
In python you have the int() function that has the ability to turn any float number to a integer.
Example:
x = 53.980
print(int(x))# 53
So if after that conversion you check if the float number is different from the converted integer number you will know if after the decimal point there are any numbers.
So 53.056 would return True while 53.000 or 53 would return False Notice the bellow function putting this in practice
def check_decimals(x):
if x != int(x):
print(f"Has decimal numbers")
else:
print(f"Does not have decimal numbers")
a = 53.06
check_decimals(a)# Has decimal numbers
b = 53.00
check_decimals(b)# Does not have decimal numbers
c = 53
check_decimals(c)# Does not have decimal numbers
So if this is what you need you can simply forget the function and do an inline statement like so:
a = 53.06
print(a != int(a))# True 'Has decimal numbers'
print(a == int(a))# False 'Does not have decimal numbers'
If in other hand you want to find out if a number has a decimal point, you can check if it is a floating point number using the isinstance method:
a = 53.00
print(isinstance(a,float))# True
print(isinstance(a,int))# False
b = 53
print(isinstance(b,float))# False
print(isinstance(b,int))# True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With