我想知道在使用字符串格式时,如何在python中舍入一个数字。在我的代码中,我使用了%r而不是%d,因为%d打印了一个整数。在使用%r时如何舍入数字?我想把我的数字四舍五入到小数点后两位。
def new_formula(value):
payment = value * 9.00
tips = payment/.29
earned = payment + tips
return payment, tips, earned
name = "Nate"
hours = 7.5
print "%s worked %r hours." % (name, hours)
print """He was paid %r dollars and made %r dollars in tips.
At the end of the day he earned %r dollars.""" % new_formula(hours)
使用函数round:
参数2告诉函数在小数点后使用2位数字。
好吧,你可以在返回语句中取整。例如,
round(payment, 2)
。而且,我不确定您为什么要使用(您能告诉我为什么吗?)。您可以使用.2f来代替两个小数位。相关问题 更多 >
编程相关推荐