【Python】round函数四舍五入的坑


 

1、round()函数四舍五入

 1 print(round(10.4))       # ==>10
 2 print(round(10.49))      # ==>10
 3 print(round(10.5))       # ==>10
 4 print(round(10.51))      # ==>11
 5 print(round(10.6))       # ==>11
 6 print('='*50)
 7 print(round(11.4))       # ==>11
 8 print(round(11.49))      # ==>11
 9 print(round(11.5))       # ==>12
10 print(round(11.51))      # ==>12
11 print(round(11.6))       # ==>12

输出结果:

10
10
10
11
11
==================================================
11
11
12
12
12

小结:

当个位为奇数,小数部分>=0.5入,其余为舍;

当个位为偶数,小数部分>0.5入,其余为舍。

 

2、使用decimal模块

 1 import decimal
 2 
 3 x = 10.3456
 4 # Context函数,有很多参数,都有默认的值,我们做四舍五入时候,只需要改变两个参数的值来设置python的context处理环境即可。
 5 # 参数1是prec参数,用来显示最终的数值位数,这个数值位数包含整数部分和小数部分。
 6 # 参数2是rounding参数,改为ROUND_HALF_UP作为四舍五入方式。
 7 # create_decimal函数,注意参数值是一个字符串,因此需要先将x转为字符串
 8 x1=decimal.Context(prec=4,rounding=decimal.ROUND_HALF_UP).create_decimal(str(x))
 9 print(x1)
10 print(type(x1))

输出结果:

10.35
<class 'decimal.Decimal'>

 

3、format()格式化输出

输出结果为字符类型的数字

1 x = 10.3456
2 print(format(x,'0.1f'))         # ==>10.3
3 print(format(x,'0.2f'))         # ==>10.3
4 print(format(x,'0.3f'))         # ==>10.3
5 print(type(format(x,'0.1f')))   # ==><class 'str'>

输出结果:

10.3
10.35
10.346
<class 'str'>

 

总结:

1、若对四舍五入的结果精度要求较高,建议使用decimal模块,不建议使用round();

2、若仅仅想格式化输出数据,format()足矣。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM