Python 四舍五入到最接近的 0.25 [重复]

问题描述 投票:0回答:2

我想将整数四舍五入到最接近的 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
python python-3.x math rounding
2个回答
28
投票

函数

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

12
投票

round
是Python 3.4中的内置函数print语法已更改。这在 Python 3.4 中工作得很好:

def x_round(x):
    print(round(x*4)/4)

x_round(11.20) == 11.25
x_round(11.12) == 11.00
x_round(11.37) == 11.50
© www.soinside.com 2019 - 2024. All rights reserved.