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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34316080/
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 14:48:27  来源:igfitidea点击:

how to round a float number to the nearest integer in Python

python

提问by fsaizpoy

The function round(x) in Python yields floating number. Therefore, what is the most appropriate code in Python to round a float to the nearest neighbor?

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

回答by Simone Zandara

It seems that round already does what you want, or maybe I did not understand the question.

似乎 round 已经做了你想要的,或者也许我没有理解这个问题。

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

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

EDIT

编辑

Python3 round returns an integer, but in Python2.7 round returns a float. For Python2.7 just do:

Python3 轮返回一个整数,但在 Python2.7 轮返回一个浮点数。对于 Python2.7,只需执行以下操作:

int(round(x))