【问题标题】:How to avoid printing scientific notation in python without adding extra digits?如何在不添加额外数字的情况下避免在 python 中打印科学计数法?
【发布时间】:2011-09-18 23:27:05
【问题描述】:

This question 询问如何在 python 中抑制科学记数法。

我有一系列数字要显示 - 10 的小幂 - 我想在显示它们时不带尾随零。 IE。 0.1、0.01 等到 0.000001

如果我这样做"%s" % 10 ** -6,我会得到'1e-06'。如果我使用"%f" % 10 ** -6,我会得到'0.000001',这就是我想要的。

但是,"%f" % 10 ** -3 产生的 '0.001000' 违反了“无尾随零”约束。

蛮力解决这个问题(正则表达式替换或其他东西)并不难,但我想知道我是否缺少一些格式字符串魔法。

【问题讨论】:

    标签: python floating-point string-formatting


    【解决方案1】:

    在我看来有点老套,但您可以使用 str.rstrip("0") 来消除尾随零:

    >>> "{:f}".format(10**-6).rstrip("0")
    '0.000001'
    >>> "{:f}".format(10**-3).rstrip("0")
    '0.001'
    

    编辑:正如 cmets 中所说,有一个更好的方法:

    >>> format(1e-6, 'f').rstrip('0')
    '0.000001'
    >>> format(1e-3, 'f').rstrip('0')
    '0.001'
    

    【讨论】:

    • 这就是 OP 所说的“蛮力解决这个问题”,所以这不是一个真正的答案 (-1)。但是,我也会这样做(+1)。
    • +1。它一点也不hacky。也许使用format() 函数会更干净一点:format(1e-6, 'f').rstrip('0')
    • @Oben Sonne,但它比使用正则表达式要好得多。 @Ferdinand Beyer,谢谢,我不知道,正在修改答案。
    • 这还不错;我忘记了 rstrip 需要一个 arg 来删除角色。
    • utdemirs 答案的较长版本:没有格式字符串选项。您必须自己编写解决方案。这还不错,因为解决方案非常简单,正如 utdemir 使用 rstrip 方法所证明的那样。
    【解决方案2】:

    简单的rstrip("0") 不能很好地处理小的和某些其他值,它应该在小数点后留下一个零 - 0.0 而不是0.

    def format_float(value, precision=-1):
        if precision < 0:
            f = "%f" % value
        else:
            f = "%.*f" % (precision, value)
    
        p = f.partition(".")
    
        s = "".join((p[0], p[1], p[2][0], p[2][1:].rstrip("0")))
    
        return s
    
    print(format_float(3e-10))
    print(format_float(3e-10, 20))
    print(format_float(1.5e-6))
    print(format_float(1.5e+6))
    

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 1970-01-01
      • 2020-09-26
      • 2020-03-02
      • 2013-04-12
      • 1970-01-01
      • 2022-01-06
      • 2012-11-30
      • 1970-01-01
      相关资源
      最近更新 更多