编程语言
首页 > 编程语言> > python怎么实现正确的浮点数四舍五入

python怎么实现正确的浮点数四舍五入

作者:互联网

以下示例展示对于结构相同的两组数据(1.035750001.03425000)保留小数后4位,使用不同方法的输出结果

from decimal import Decimal, ROUND_HALF_UP

print(round(1.03575000, 4))
print(round(1.03425000, 4))
print('--------------------')
print(round(Decimal("1.03575000"), 4))
print(round(Decimal('1.03425000'), 4))
print('--------------------')
print(Decimal("1.03575000").quantize(Decimal("0.0000"), rounding=ROUND_HALF_UP))
print(Decimal("1.03425000").quantize(Decimal("0.0000"), rounding=ROUND_HALF_UP))

"""
1.0357
1.0342
--------------------
1.0358
1.0342
--------------------
1.0358
1.0343
"""

标签:四舍五入,python,浮点数,1.03425000,round,--------------------,print,1.03575000,Decimal
来源: https://www.cnblogs.com/rong-z/p/16204124.html