在python中将浮点数四舍五入到最接近的0.5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24838629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:19:03  来源:igfitidea点击:

round off float to nearest 0.5 in python

python

提问by Yin Yang

I'm trying to round off floating digits to the nearest 0.5

我正在尝试将浮动数字四舍五入到最接近的 0.5

For eg.

例如。

1.3 -> 1.5
2.6 -> 2.5
3.0 -> 3.0
4.1 -> 4.0

This is what I'm doing

这就是我正在做的

def round_of_rating(number):
        return round((number * 2) / 2)

This rounds of numbers to closest integer. What would be the correct way to do this?

这会将数字舍入到最接近的整数。这样做的正确方法是什么?

采纳答案by faester

Try to change the parenthesis position so that the rounding happens before the division by 2

尝试更改括号位置,以便在除以 2 之前进行舍入

def round_of_rating(number):
    """Round a number to the closest half integer.
    >>> round_of_rating(1.3)
    1.5
    >>> round_of_rating(2.6)
    2.5
    >>> round_of_rating(3.0)
    3.0
    >>> round_of_rating(4.1)
    4.0"""

    return round(number * 2) / 2

Edit:Added a doctestable docstring:

编辑:添加了一个doctest能够的文档字符串:

>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)