python round函数 竟然把5舍去了
Python 3.6.1 (default, Sep7 2017, 16:36:03)[GCC 6.3.0 20170406] on linuxType "help", "copyright", "credits" or "license" for more information.>>> round(3.5)4>>> round(3.55, ...
·
Python 3.6.1 (default, Sep 7 2017, 16:36:03)
[GCC 6.3.0 20170406] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> round(3.5)
4
>>> round(3.55, 1)
3.5
为什么?据说这跟浮点数的精度有关。我们看到的这个3.55实际上在机器上存储的值是3.54999...999
最终, 我手动写了一个round函数:
def round(n, m=0):
'''round(3.555, 2) => 3.56'''
# python自带的round函数有时会把5舍掉,如round(3.55, 1) => 3.5
if m == 0:
return int(n+0.5)
n = str(int(n*10**m+0.5))
m *= -1
n = '{}.{}'.format(n[:m], n[m:])
return float(n)
----------------
2019-12-15 先转为str类型,再运用decimal将代码精简如下:
from decimal import Decimal, ROUND_HALF_UP
def precise_round(n, m=0, deci=False):
d = Decimal(str(n)).quantize(Decimal('0.{}'.format('0'*m)), ROUND_HALF_UP)
return d if deci else float(d)
---------------------
Updated_at 2020/07/20
def to_decimal(amount: Union[int, str, float, Decimal]) -> Decimal:
"""将传入的数值,四舍五入转化为两个小数的Decimal对象
Usage::
>>> to_decimal(1.565)
Decimal('1.57')
>>> to_decimal('1.564')
Decimal('1.56')
"""
return Decimal(str(amount)).quantize(Decimal("0.00"), ROUND_HALF_UP)
更多推荐
已为社区贡献1条内容
所有评论(0)