关于python浮点数的精度问题。

若想严格按照四舍五入进行,可使用Decimal,代码如下:

1 from decimal import Decimal, ROUND_HALF_UP
2 
3 def round(x, n):
4     return Decimal(x).quantize(Decimal(n), ROUND_HALF_UP)
>>> roundx("1.24", ".1")
Decimal('1.2')

>>> roundx("1.25", ".1")
Decimal('1.3')
>>> roundx("1.26", ".1")
Decimal('1.3')
>>> roundx("1.245", ".01")
Decimal('1.25')
>>> roundx("2.675", ".01")
Decimal('2.68')
>>> roundx("2.375", ".01")
Decimal('2.38')

另外创建Decimal实例时,应该传入一个准确数值,比如整数或字符串等。

posted on 2018-04-05 20:49  Guo磊  阅读(1250)  评论(0编辑  收藏  举报

导航