Python - 四舍五入到四分之一间隔

21

我遇到了以下问题:

有各种数字,例如:

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 ?

还是说我可以动手写一个函数来实现这个任务?

先感谢您的帮助,祝好

敬礼,

Dan

4个回答

35

这是一个通用的解决方案,允许将数字四舍五入到任意分辨率。对于你的特定情况,你只需要提供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

一个优美的通用解决方案。如何将所有给定的解决方案标记为“已接受的答案”? - Daniyal
4
@Daniyal:你做不到。如果答案不能根据其价值排序,我的通常做法是将其(与点赞一起)给予声望最低的人,并同时点赞其他人。但在这种情况下,不幸的是我不是声望最低的那个人。 - paxdiablo

32
>>> 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
>>> 

头撞桌——确实有点琐碎——我要在凌晨5点停止编码了-.- 谢谢pulegium和6502。 - Daniyal

4

虽然没有内置函数,但编写这样的函数非常简单。

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

3

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

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

所以现在这个函数是“数据类型敏感”的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接