为了账号安全,请及时绑定邮箱和手机立即绑定

Python打印出浮点数或整数

Python打印出浮点数或整数

慕慕森 2021-03-17 13:13:19
如果结果为小数,如何打印浮点数;如果结果没有小数,如何打印整数?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-dbs1ocbc1 = ((c/float(100))*15)ocbc2 = c-ocbc1if (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: 250Enter the bank of your credit card (DBS, OCBC, etc.): OCBCPlease pay $212.5Enter the total cost of purchase: 250Enter the bank of your credit card (DBS, OCBC, etc.): DBSPlease pay $225.0
查看完整描述

3 回答

?
30秒到达战场

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


查看完整回答
反对 回复 2021-03-24
?
波斯汪

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


查看完整回答
反对 回复 2021-03-24
  • 3 回答
  • 0 关注
  • 271 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信