round()是python自带的一个函数,用于数字的四舍五入。

但是round()的输出结果与Python的版本有关:

在python3中,round(1.0/2.0)=0;在python2中,round(1.0/2.0)=1

$ 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)

  1. digits>0,四舍五入到指定的小数位
  2. digits=0, 四舍五入到最接近的整数
  3. digits<0 ,在小数点左侧进行四舍五入
  4. 如果round()函数只有number这个参数,等同于digits=0

四舍五入规则:

  1. 要求保留位数的后一位<=4,则舍去3,如5.214保留小数点后两位,结果是5.21
  2. 要求保留位数的后一位“=5”,且该位数后面没有数字,则不进位,如5.215,结果为5.21
  3. 要求保留位数的最后一位“=5”,且该位数后面有数字,则进位,如5.2151,结果为5.22
  4. 要求保留位数的最后一位“>=6”,则进位。如5.216,结果为5.22

例子:

    

 

 

 

 

 

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐