Python舍入到最接近的0.25 [英] Python round to nearest 0.25
本文介绍了Python舍入到最接近的0.25的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将整数四舍五入为最接近的0.25个十进制值,如下所示:
I want to round integers to the nearest 0.25 decimal value, like this:
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错误:
This gives me the following error in Python:
Invalid syntax
推荐答案
函数math.round
不存在,只需使用内置的round
The function math.round
does not exist, just use the built in round
def x_round(x):
print(round(x*4)/4)
请注意,print
是Python 3中的一个函数,因此需要括号.
Note that print
is a function in Python 3, so the parentheses are required.
目前,您的函数未返回任何内容.最好从函数中返回值,而不是打印出来.
At the moment, your function doesn't return anything. It might be better to return the value from your function, instead of printing it.
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
这篇关于Python舍入到最接近的0.25的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文