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

时间:2015-12-16 15:37:16

标签: python

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

1 个答案:

答案 0 :(得分:17)

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

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

>>> a = round(3.8)
>>> type(a)
<class 'int'>

修改

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

int(round(x))