Python打印出浮点数或整数

Kir*_*Sim 3 python if-statement coding-style string-formatting

如果结果有小数,我如何打印出浮点数或如果结果没有小数则打印出整数?

c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1


if (c > 200):
    if (bank == 'DBS'):
        print('Please pay $'+str(dbs2))
    elif (bank == 'OCBC'):
        print('Please pay $'+str(ocbc2))
    else:
        print('Please pay $'+str(c))
else:
    print('Please pay $'+str(c))

exit = raw_input("Enter to exit")
Run Code Online (Sandbox Code Playgroud)

例如,结果

Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): OCBC
Please pay $212.5

Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): DBS
Please pay $225.0
Run Code Online (Sandbox Code Playgroud)

bba*_*les 5

Python 浮点数有一个内置方法来确定它们是否是整数:

x = 212.50
y = 212.0
f = lambda x: int(x) if x.is_integer() else x
print(x, f(x), y, f(y), sep='\t')
>> 212.5    212.5   212.0   212
Run Code Online (Sandbox Code Playgroud)


πόδ*_*κύς 5

您可以尝试这个,它只使用Python的字符串格式化方法:

if int(c) == float(c):
    decimals = 0
else:
    decimals = 2 # Assumes 2 decimal places for money

print('Please pay: ${0:.{1}f}'.format(c, decimals))
Run Code Online (Sandbox Code Playgroud)

如果出现以下情况,将提供以下输出c == 1.00:

Please pay: $1
Run Code Online (Sandbox Code Playgroud)

或者输出如果c == 20.56:

Please pay: $20.56
Run Code Online (Sandbox Code Playgroud)


Muh*_*mir 5

由于现在有一种更简单的方法,并且这篇文章是第一个结果,因此人们应该了解它:

print(f"{3.0:g}")  # 3
print(f"{3.14:g}")  # 3.14
Run Code Online (Sandbox Code Playgroud)