Python中如何使用round方法

796次阅读
没有评论

Python中如何使用round方法

round函数是一个用于四舍五入的函数;

在python3中,round(1.0/2.0)得到的是1,而在python2中,round(1.0/2.0)得到的是0

$ python
Python 2.7.8 (default, Jun 18 2015, 18:54:19) 
[GCC 4.9.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
1.0
$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.5)
0

使用的一般语法是round(number,digits)

number,要四舍五入的数,digits是要小数点后保留的位数

如果 digits 大于 0,则四舍五入到指定的小数位。 
如果 digits 等于 0,则四舍五入到最接近的整数。 
如果 digits 小于 0,则在小数点左侧进行四舍五入。
如果round函数只有参数number,等同于digits 等于 0。

返回的值是四舍五入后的值

其四舍五入的规矩一般为如下:

(1)要求保留位数的后一位如果是4或者4以下的数字,则舍去, 例如 5.214保留两位小数为5.21。
(2)如果保留位数的后一位如果是6或者6以上的数字,则进上去, 例如5.216保留两位小数为5.22。
(3)如果保留位数的后一位如果是5,且该位数后没有数字。 例如5.215保留两位小数为5.21,5.225保留两位小数为5.22。
(4) 如果保留位数的后一位如果是5,且该位数后有数字。则进上去,例如5.2152保留两位小数为5.22,5.2252保留两位小数为5.23,
5.22500001保留两位小数为5.23。
>>> round(5.215,2)
5.21
>>> round(5.225,2)
5.22
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python基础教程2022-12-07发表,共计914字。
新手QQ群:570568346,欢迎进群讨论 Python51学习