在 Python 中四舍五入到 5(或其他数字) [英] Round to 5 (or other number) in Python

查看:52
本文介绍了在 Python 中四舍五入到 5(或其他数字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可以像下面这样舍入的内置函数?

Is there a built-in function that can round like the following?

10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20

推荐答案

我不知道 Python 中的标准函数,但这对我有用:

I don't know of a standard function in Python, but this works for me:

def myround(x, base=5):
    return int(base * round(float(x)/base))

Python3

def myround(x, base=5):
    return base * round(x/base)

很容易理解为什么上述方法有效.你想确保你的数字除以 5 是一个整数,正确四舍五入.所以,我们首先这样做(round(float(x)/5) 其中 float 只在 Python2 中需要),然后因为我们除以 5,我们乘以也到 5.最终转换为 int 是因为 round() 在 Python 2 中返回一个浮点值.

It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(float(x)/5) where float is only needed in Python2), and then since we divided by 5, we multiply by 5 as well. The final conversion to int is because round() returns a floating-point value in Python 2.

我通过给它一个 base 参数使函数更通用,默认为 5.

I made the function more generic by giving it a base parameter, defaulting to 5.

这篇关于在 Python 中四舍五入到 5(或其他数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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