3 回答

TA貢獻1828條經驗 獲得超6個贊
您可以嘗試使用簡單的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))
如果滿足以下條件,則將為您提供以下輸出c == 1.00:
Please pay: $1
或此輸出,如果c == 20.56:
Please pay: $20.56

TA貢獻1811條經驗 獲得超4個贊
def nice_print(i):
print '%.2f' % i if i - int(i) != 0 else '%d' % i
nice_print(44)
44
nice_print(44.345)
44.34
在您的代碼中:
def nice_number(i):
return '%.2f' % i if i - int(i) != 0 else '%d' % i
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 $'+nice_number(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+nice_number(ocbc2))
else:
print('Please pay $'+nice_number(c))
else:
print('Please pay $'+nice_number(c))
添加回答
舉報