python四舍五入的方法
用round:
print(round(2.675, 2)
#结果为:2.67
后面的2表示保留两位小数。
round不能完全四舍五入的原因,二进制的误差问题。
解决方法:
1.把小数扩大100倍,再缩小100倍,但某些情况还是有误差。
2.引入decimal.Decimal
from _pydecimal import Decimal, Context, ROUND_HALF_UP
print(Context(prec=3, rounding=ROUND_HALF_UP).create_decimal('1.325'))
#打印结果:
#1.33
以上代码,以后直接拿过来用吧。其中的 3 表示总的位数,1.325写成自己的数
来自:
1.四舍五入就用round( )?Python四舍五入的正确打开方式!:https://blog.csdn.net/qq_39234705/article/details/82817703
2.python3:小数位的四舍五入(用两种方法解决round 遇5不进):https://blog.csdn.net/qq_34979346/article/details/83827044
|