Python - 按四分之一间隔舍入

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

我遇到了以下问题:

给出各种数字,例如:

10.38

11.12

5.24

9.76

是否存在一个已经存在的“内置”函数来将它们四舍五入到最接近的

0.25
步骤,例如:

10.38 --> 10.50

11.12 --> 11.00

5.24  --> 5.25

9.76  --> 9-75

或者我可以继续编写一个执行所需任务的函数吗?

python rounding intervals
4个回答
38
投票

这是一个通用解决方案,允许舍入到任意分辨率。对于您的具体情况,您只需提供

0.25
作为分辨率,但其他值也是可能的,如测试用例所示。

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

print "Rounding to quarters"
print roundPartial (10.38, 0.25)
print roundPartial (11.12, 0.25)
print roundPartial (5.24, 0.25)
print roundPartial (9.76, 0.25)

print "Rounding to tenths"
print roundPartial (9.74, 0.1)
print roundPartial (9.75, 0.1)
print roundPartial (9.76, 0.1)

print "Rounding to hundreds"
print roundPartial (987654321, 100)

输出:

Rounding to quarters
10.5
11.0
5.25
9.75
Rounding to tenths
9.7
9.8
9.8
Rounding to hundreds
987654300.0

33
投票
>>> def my_round(x):
...  return round(x*4)/4
... 
>>> 
>>> assert my_round(10.38) == 10.50
>>> assert my_round(11.12) == 11.00
>>> assert my_round(5.24) == 5.25
>>> assert my_round(9.76) == 9.75
>>> 

4
投票

没有内置函数,但这样的函数写起来很简单

def roundQuarter(x):
    return round(x * 4) / 4.0

3
投票

paxdiablo 的解决方案可以稍微改进一下。

def roundPartial (value, resolution):
return round (value /float(resolution)) * resolution

所以该函数现在是:“数据类型敏感”。

© www.soinside.com 2019 - 2024. All rights reserved.