2024-05-14 02:35:26 发布
网友
我遇到了以下问题:
给定各种数字,例如:
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?
或者我可以继续并一起黑客功能,执行所需的任务?
提前谢谢
致以最诚挚的问候
丹
没有内置函数,但是这样的函数编写起来很简单
def roundQuarter(x): return round(x * 4) / 4.0
这是一个通用的解决方案,允许舍入到任意分辨率。对于您的特定情况,您只需要提供0.25作为解析,但其他值是可能的,如测试用例中所示。
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
>>> 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 >>>
没有内置函数,但是这样的函数编写起来很简单
这是一个通用的解决方案,允许舍入到任意分辨率。对于您的特定情况,您只需要提供
0.25
作为解析,但其他值是可能的,如测试用例中所示。这将输出:
相关问题 更多 >
编程相关推荐