Python打印出 float 或整数

标签 python coding-style string-formatting if-statement

如果结果有小数,我如何打印出 float ;如果结果没有小数,我如何打印出整数?

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

最佳答案

你可以试试这个,它简单地使用了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

关于Python打印出 float 或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577669/

相关文章:

c# - 如何处理冲突的编码约定?

python - 如何在Python中以更简洁的方式传递多个参数

java - 我应该把@Transactional注释: at an interface definition or at an implementing class?放在哪里

c# - 在 C# 中,如何在不使负值变长的情况下使用零填充格式化整数?

python - 如何使用 while 循环创建乘法表?

python - 将 Python 代码转换为适用于 Android 的 apk?

python - RDS : Not able to fetch events it is showing blank in boto3 describe_events

python - 痛饮 C++/Python : inheritance proxy objects

c# - 在字符串 : "Input string was not in a correct format" 中使用括号时

asp.net-mvc - ASP.NET MVC 显示格式不会将 DateTime 格式化为日期字符串