Dan*_*yal 17 python rounding intervals
我遇到了以下问题:
鉴于各种数字,如:
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?
或者我可以继续将一个执行所需任务的功能组合在一起吗?
在此先感谢
最诚挚的问候
担
pax*_*blo 29
这是一种通用解决方案,允许舍入到任意分辨率.对于您的特定情况,您只需要提供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)
Run Code Online (Sandbox Code Playgroud)
这输出:
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
Run Code Online (Sandbox Code Playgroud)
ryt*_*tis 27
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
没有内置,但这样的功能写得很简单
def roundQuarter(x):
return round(x * 4) / 4.0
Run Code Online (Sandbox Code Playgroud)