[Python]round四舍五入精度缺失的处理

对python四舍五入的处理方案

征象:平常的四舍五入操纵都是运用内置的round要领

In [14]: round(2.675,2)  
Out[14]: 2.67  

文档中如许诠释的

The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero. Since the decimal fraction 2.675 is exactly halfway between 2.67 and 2.68, you might expect the result here to be (a binary approximation to) 2.68. It’s not, because when the decimal string 2.675 is converted to a binary floating-point number, it’s again replaced with a binary approximation, whose exact value is

In [22]: Decimal(2.675)
Out[22]: Decimal('2.67499999999999982236431605997495353221893310546875')

所以关于精度有明确要求的数学盘算来讲,运用round是不可的

google中有人这么处理的:

>>> from decimal import Decimal
>>> n = Decimal('1.555')
>>> round(n, 2)
Decimal('1.56')

如今运用的体式格局是:
能够运用str.format来格式化数字完成四舍五入

from decimal import Decimal
In [15]: '{:.2f}'.format(Decimal('2.675'))
Out[15]: '2.68''

毛病的写法

In [12]: '{:.2f}'.format(2.675)
Out[12]: '2.67'
In [13]: '{:.2f}'.format('2.675')
-------------------------------------------------------------
ValueError                                Traceback (most recent call last)
In [14]: '{:.2f}'.format(Decimal(2.675))
Out[14]: '2.67'

转自:orangleliu的博客

    原文作者:Nerve
    原文地址: https://segmentfault.com/a/1190000000338205
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞