我遇到了以下问题:
给定各种数字,例如:
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 ?
或者我可以继续编写一个执行所需任务的函数吗?
提前感谢和
致以最诚挚的问候
丹
最佳答案
这是一种通用解决方案,允许四舍五入到任意分辨率。对于您的具体情况,您只需要提供 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
关于Python - 按四分之一间隔舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8118679/