3

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

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
4

4 回答 4

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
于 2013-05-16T01:50:10.353 回答
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))

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

Please pay: $1

或者这个输出,如果c == 20.56

Please pay: $20.56
于 2013-05-16T01:52:14.417 回答
2

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

print(f"{3.0:g}")  # 3
print(f"{3.14:g}")  # 3.14
于 2020-11-04T12:36:53.617 回答
1
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))
于 2013-05-16T01:48:42.523 回答