Python - 按四分之一间隔舍入

标签 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 ?

或者我可以继续编写一个执行所需任务的函数吗?

提前感谢和

致以最诚挚的问候

最佳答案

这是一种通用解决方案,允许四舍五入到任意分辨率。对于您的具体情况,您只需要提供 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/

相关文章:

java - 高效的 BigDecimal 上下舍入到两位小数

mysql - 查看最近x天是否没有创建记录

javascript - 基本的 Javascript 倒计时

python - 填充在 Mongoengine 中,引用字段

python - scipy.io.loadmat 嵌套结构(即字典)

python - 有没有办法覆盖pytest(python)中的默认断言?

python - List 在 Python 中真的是不变的吗

c - 如何在 C 中进行舍入?

c# - 移动到圆形区域,然后捕捉到网格?

mysql - 用不连续的日期更新年度变化