Python - 按四分之一间隔舍入 [英] Python - Rounding by quarter-intervals

查看:149
本文介绍了Python - 按四分之一间隔舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题:



给出各种数字,如:



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


I'm running into the following issue:

Given various numbers like:

10.38

11.12

5.24

9.76

does an already 'built-in' function exists to round them up to the closest 0.25 step like e.g.:

10.38 --> 10.50

11.12 --> 11.00

5.24 --> 5.25

9.76 --> 9-75 ?

Or can I go ahead and hack together a function that performs the desired task?

Thanks in advance and

with best regards

Dan

解决方案

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

这篇关于Python - 按四分之一间隔舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆