我想将整数四舍五入到最接近的 0.25 小数值,如下所示:
import math
def x_round(x):
print math.round(x*4)/4
x_round(11.20) ## == 11.25
x_round(11.12) ## == 11.00
x_round(11.37) ## == 11.50
这在 Python 中给了我以下错误:
Invalid syntax
函数
math.round
不存在,只需使用内置的round
def x_round(x):
print(round(x*4)/4)
请注意,
print
是Python 3中的函数,因此需要括号。
目前,您的函数没有返回任何内容。从函数中返回值可能比打印它更好。
def x_round(x):
return round(x*4)/4
print(x_round(11.20))
如果您想向上舍入,请使用
math.ceil
。
def x_round(x):
return math.ceil(x*4)/4