ITPub博客

首页 > IT职业 > IT图书 > round四舍五入详解--python2与python3版本间区别

round四舍五入详解--python2与python3版本间区别

IT图书 作者:huzhizhong 时间:2021-09-09 09:42:50 0 删除 编辑

round()方法返回 数值 的小数点四舍五入到n个数字。

语法

以下是round()方法的语法:

round( x [, n] )


参数

    x --这是一个数值,表示需要格式化的数值

    n --这也是一个数值,表示小数点后保留多少位

返回值

该方法返回 数值x 的小数点四舍五入到n个数字

PS: round 对传入的数据进行四舍五入,如果ngigits不传,默认是0(就是说保留整数部分).ngigits


例子

下面的例子显示了round()方法的使用

#!/usr/bin/python2
print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)


当我们运行上面的程序,它会产生以下结果:

round(80.23456, 2) : 80.23
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0


Python3和Python2版本的区别


Python2把x四舍五入为远离0的最近倍数,如round(0.5)=1, round(-0.5)=-1;

Python3则会把x四舍五入为最近的偶数倍数,如round(0.5)=0, round(1.5)=2.0, round(2.5)=2.0

代码:

#!/usr/bin/python2
print round(2.635, 2)
print round(2.645, 2)
print round(2.655, 2)
print round(2.665, 2)
print round(2.675, 2)


输出结果:

2.63
2.65
2.65
2.67
2.67


round方法缺陷


通过上面的例子大家可以发现, round的四舍五入方法貌似和我们理解的不太一样, 其实这个不是round的bug, 这个主要来自输入时十进制转换为计算机内部二进制时,且这个问题在有限精度下不可能解决,也不需要解决。


Python 的 decimal 模块可用于解决这一问题。


如果大家不需要四舍五入的话,也可以考虑使用我们最熟悉的print("%.2f" % 2.675)这种方式实现。

原文来源:https://m.pythontab.com/article/1075


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1446/viewspace-2806418/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    107
  • 访问量
    921