在python中使用字符串格式时舍入一个数字

在python中使用字符串格式时舍入一个数字,python,string,formatting,rounding,Python,String,Formatting,Rounding,我想知道如何在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" h

我想知道如何在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)

使用函数轮:

print "%s worked %.2f hours." % (name, round(hours, 2))

参数2告诉函数在小数点后使用两位数字。

好的,您可以对return语句进行四舍五入。例如,
round(payment,2)
。而且,我不确定您为什么要使用\r。(你能告诉我为什么吗?)。您可以使用%.2f来代替小数点后两位。

我不确定您是否要使用
%r
--为什么不使用
%.2f
%0.2f
?此外,python的内置函数可能会有所帮助。我以前没有见过这些函数。我会尝试一下。如果我要使用round(),我会把要四舍五入的数字放在括号中,然后四舍五入到什么位置,比如round(值,2)?我使用了%r,因为我在参加的在线课程中被告知要使用它。我知道%s会将字符串传递到我要打印的内容中,%d和%r会传递数字。但我实际上不明白它们的区别。在你回答之前我不知道%r的意思。它创建了一个对象的表示,该对象有利于调试,但不利于向用户显示,因为它将在结果周围显示“字符”。通常,您希望使用%s显示字符串,使用%d显示整数,使用%f传递实数。