Python打印出浮点数或整数

发布于 2021-01-29 15:00:32

如果结果为小数,如何打印浮点数;如果结果没有小数,如何打印整数?

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")

示例结果

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
关注者
0
被浏览
65
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以尝试使用简单的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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看