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")
编辑:好的,所以因为"检查后面的小数是"带来一些困惑,让我解释一下。我希望能够检查一个数字是否有小数。例如,7/3(foo)给出了小数,但我希望python告诉我没有我必须做数学。忘了"哪个十进制"部分
答案 0 :(得分:2)
如果你只想测试一个除法是否有小数,只需检查模数:
foo = a % b
if foo != 0:
# Then foo contains decimals
pass
if foo == 0:
# Then foo does NOT contain decimals
pass
然而(因为你的问题有点不清楚)如果你想分割整数和小数部分,那么使用math.modf()
函数:
import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)
答案 1 :(得分:0)
根据您问题的措辞,我假设您正在查看小数点后是否有某个数字?如果是这样的话......
你可以做的是使用.
作为分隔符来分割foo并检查数字(在这种情况下你正在寻找3)是否在.
之后的部分
foo = 7/float(3)
foo = str(foo)
after_decimal = foo.split('.')[1]
if '3' in after_decimal:
print 'Yes!'
else:
print 'No!'
In this case the output is: Yes!
答案 2 :(得分:0)
你的问题有点不清楚。但是这段代码可能会让你朝着正确的方向前进。只需致电Decimal_Checker
并输入您想要的号码。
def Decimal_Checker(x,y):
if x %y != 0:
print("it has decimals")
else:
print("it does not have decimals")
Decimal_Checker(3,2)