python 准确进行四舍五入的问题,头痛!

penond 2018-09-14 11:02:38
现在有2个数字 2.675 和 4.005,对其四舍五入到小数点后2位,理论上应该是 2.68 和 4.01,但竟然实现不了!!!!

代码:
from decimal import Decimal

print(round(2.675,2))
print(round(4.005,2))

print('{:.2f}'.format(Decimal('2.675')))
print('{:.2f}'.format(Decimal('4.005')))

输出:
2.67(错误)
4.0(错误)

2.68(正确)
4.00(错误)

不论round 还是 format(Decimal()) 输出都是错误的!请教高手救急。。。。
...全文
2797 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
漫书 2020-04-01
  • 打赏
  • 举报
回复
彻底解决的话,需要分析舍入策略和浮点数精度问题:https://blog.csdn.net/wangxichang/article/details/90606211
  • 打赏
  • 举报
回复


def new_round(_float, _len):
    """
    Parameters
    ----------
    _float: float
    _len: int, 指定四舍五入需要保留的小数点后几位数为_len
    
    Returns
    -------
    type ==> float, 返回四舍五入后的值
    """
    if isinstance(_float, float):
        if str(_float)[::-1].find('.') <= _len:
            return(_float)
        if str(_float)[-1] == '5':
            return(round(float(str(_float)[:-1]+'6'), _len))
        else:
            return(round(_float, _len))
    else:
        return(round(_float, _len))

  • 打赏
  • 举报
回复
引用 4 楼 热苏斯是有潜力超越姆巴佩的 的回复:
def new_round(_float, _len): if str(_float)[-1] == '5': return(round(float(str(_float)[:-1]+'6'), _len)) else: return(round(_float, _len))
这个不太对哈。。。 改了下: ===================================== def new_round(_float, _len): """ Parameters ---------- _float: float _len: int, 指定四舍五入需要保留的小数点后几位数为_len Returns ------- type ==> float, 返回四舍五入后的值 """ if isinstance(_float, float): if str(_float)[::-1].find('.') <= _len: return(_float) if str(_float)[-1] == '5': return(round(float(str(_float)[:-1]+'6'), _len)) else: return(round(_float, _len)) else: return(round(_float, _len))
  • 打赏
  • 举报
回复
def new_round(_float, _len): if str(_float)[-1] == '5': return(round(float(str(_float)[:-1]+'6'), _len)) else: return(round(_float, _len))
流泪熊猫头 2018-09-22
  • 打赏
  • 举报
回复
关于这个问题,我专门写了篇文章:https://blog.csdn.net/qq_39234705/article/details/82817703 可以参考下
流泪熊猫头 2018-09-22
  • 打赏
  • 举报
回复
round()函数只有一个参数,不指定位数的时候,返回一个整数,而且是最靠近的整数,类似于四舍五入,当指定取舍的小数点位数的时候,一般情况也是使用四舍五入的规则,但是碰到.5的情况时,如果要取舍的位数前的小数是奇数,则直接舍弃,如果是偶数则向上取舍。 原因就是部分小数无法用二进制完整表示,如1.15,转为二进制将是很长的一串数字。若想四舍五入保留两位小数,可以将数值乘以100再除以100.0: print(round(2.675 * 100) / 100.0) print(round(4.005 * 100) / 100.0)
penond 2018-09-14
  • 打赏
  • 举报
回复
难道只能转字符串进行处理?悲剧。。

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧