【问题标题】:Force python to not output a float in standard form / scientific notation / exponential form [duplicate]强制python不以标准形式/科学记数法/指数形式输出浮点数[重复]
【发布时间】:2011-12-01 17:40:44
【问题描述】:

所以这很好用:

>>> float(1.0e-1)
0.10000000000000001

但是当处理更大的数字时,它不会打印:

>>> float(1.0e-9)
1.0000000000000001e-09

有没有办法强制这样做?也许使用 numpy 什么的。

【问题讨论】:

    标签: python


    【解决方案1】:
    print '{0:.10f}'.format(1.0e-9)
    

    String formatting 在文档中。

    【讨论】:

    • 在 Python 2.6 之前不起作用(这没什么大不了的,但你应该提到它)。更严重的是,这修复了小数点后的位数,这可能不是 OP 想要的。
    【解决方案2】:

    建议使用f 字符串格式代码的每个人都隐含地假设可以固定小数点后的位数。对我来说,这似乎是一个非常不稳定的假设。但是,如果您不做出这样的假设,则没有内置机制可以做您想做的事情。这是我在遇到类似问题时想到的最好的技巧(在 PDF 生成器中——PDF 中的数字不能使用指数表示法)。你可能想把所有的bs 从字符串中去掉,这里可能还有其他 Python3-isms。

    _ftod_r = re.compile(
        br'^(-?)([0-9]*)(?:\.([0-9]*))?(?:[eE]([+-][0-9]+))?$')
    def ftod(f):
        """Print a floating-point number in the format expected by PDF:
        as short as possible, no exponential notation."""
        s = bytes(str(f), 'ascii')
        m = _ftod_r.match(s)
        if not m:
            raise RuntimeError("unexpected floating point number format: {!a}"
                               .format(s))
        sign = m.group(1)
        intpart = m.group(2)
        fractpart = m.group(3)
        exponent = m.group(4)
        if ((intpart is None or intpart == b'') and
            (fractpart is None or fractpart == b'')):
            raise RuntimeError("unexpected floating point number format: {!a}"
                               .format(s))
    
        # strip leading and trailing zeros
        if intpart is None: intpart = b''
        else: intpart = intpart.lstrip(b'0')
        if fractpart is None: fractpart = b''
        else: fractpart = fractpart.rstrip(b'0')
    
        if intpart == b'' and fractpart == b'':
            # zero or negative zero; negative zero is not useful in PDF
            # we can ignore the exponent in this case
            return b'0'
    
        # convert exponent to a decimal point shift
        elif exponent is not None:
            exponent = int(exponent)
            exponent += len(intpart)
            digits = intpart + fractpart
            if exponent <= 0:
                return sign + b'.' + b'0'*(-exponent) + digits
            elif exponent >= len(digits):
                return sign + digits + b'0'*(exponent - len(digits))
            else:
                return sign + digits[:exponent] + b'.' + digits[exponent:]
    
        # no exponent, just reassemble the number
        elif fractpart == b'':
            return sign + intpart # no need for trailing dot
        else:
            return sign + intpart + b'.' + fractpart
    

    【讨论】:

      【解决方案3】:

      这是非常标准的打印格式,专门用于浮点数:

      print "%.9f" % 1.0e-9
      

      【讨论】:

        【解决方案4】:

        这是 zwol 的答案简化并转换为标准 python 格式:

        import re
        def format_float_in_standard_form(f):
            s = str(f)
            m = re.fullmatch(r'(-?)(\d)(?:\.(\d+))?e([+-]\d+)', s)
            if not m:
                return s
            sign, intpart, fractpart, exponent = m.groups('')
            exponent = int(exponent) + 1
            digits = intpart + fractpart
            if exponent < 0:
                return sign + '0.' + '0'*(-exponent) + digits
            exponent -= len(digits)
            return sign + digits + '0'*exponent + '.0'
        

        【讨论】:

          【解决方案5】:
          >>> a
          1.0000000000000001e-09
          >>> print "heres is a small number %1.9f" %a
          heres is a small number 0.000000001
          >>> print "heres is a small number %1.13f" %a
          heres is a small number 0.0000000010000
          >>> b
          11232310000000.0
          >>> print "heres is a big number %1.9f" %b
          heres is a big number 11232310000000.000000000
          >>> print "heres is a big number %1.1f" %b
          heres is a big number 11232310000000.0
          

          【讨论】:

            【解决方案6】:

            打印您的号码时使用 %e:

            >>> a = 0.1234567
            >>> print 'My number is %.7e'%a
            My number 1.2345670e-01
            

            如果您使用 %g,它将自动为您选择最佳可视化:

            >>> print 'My number is %.7g'%a
            My number is 0.1234567
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-08-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多