如何在Python中将浮点数舍入到最接近的整数

fsa*_*poy 0 python

Python中的函数round(x)产生浮点数.因此,Python中用于将浮点数舍入到最近邻居的最合适的代码是什么?

Sim*_*ara 18

似乎圆已经做了你想要的,或者我可能不理解这个问题.

>>> round(3.2)
3
>>> round(3.8)
4

>>> a = round(3.8)
>>> type(a)
<class 'int'>
Run Code Online (Sandbox Code Playgroud)

编辑

Python3 round返回一个整数,但在Python2.7 round中返回一个float.对于Python2.7,只需:

int(round(x))
Run Code Online (Sandbox Code Playgroud)

  • 在 python 3 中,round(1.5) = 2 但 round(2.5) = 2 (3认同)