我如何格式化一个浮点数,使它不包含尾随零?换句话说,我希望得到的字符串尽可能短。

例如:

3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"

当前回答

对于float,你可以使用这个:

def format_float(num):
    return ('%i' if num == int(num) else '%s') % num

测试:

>>> format_float(1.00000)
'1'
>>> format_float(1.1234567890000000000)
'1.123456789'

Decimal参见解决方案:https://stackoverflow.com/a/42668598/5917543

其他回答

你可以使用%g来实现:

'%g'%(3.140)

或者,Python≥2.6:

'{0:g}'.format(3.140)

或者,Python≥3.6:

f'{3.140:g}'

格式:g cause (among other things)

不重要的后面的零[是] 从意义上移除,和 如果有,小数点也会被移除 后面没有剩余数字。

使用QuantiPhy包是一种选项。通常QuantiPhy用于 使用数字单位和SI比例因子,但它有各种 不错的数字格式选项。

    >>> from quantiphy import Quantity

    >>> cases = '3 3. 3.0 3.1 3.14 3.140 3.14000'.split()
    >>> for case in cases:
    ...    q = Quantity(case)
    ...    print(f'{case:>7} -> {q:p}')
          3 -> 3
         3. -> 3
        3.0 -> 3
        3.1 -> 3.1
       3.14 -> 3.14
      3.140 -> 3.14
    3.14000 -> 3.14

在这种情况下,它不会使用e符号:

    >>> cases = '3.14e-9 3.14 3.14e9'.split()
    >>> for case in cases:
    ...    q = Quantity(case)
    ...    print(f'{case:>7} -> {q:,p}')
    3.14e-9 -> 0
       3.14 -> 3.14
     3.14e9 -> 3,140,000,000

您可能更喜欢的另一种选择是使用SI比例因子,可能带有单位。

    >>> cases = '3e-9 3.14e-9 3 3.14 3e9 3.14e9'.split()
    >>> for case in cases:
    ...    q = Quantity(case, 'm')
    ...    print(f'{case:>7} -> {q}')
       3e-9 -> 3 nm
    3.14e-9 -> 3.14 nm
          3 -> 3 m
       3.14 -> 3.14 m
        3e9 -> 3 Gm
     3.14e9 -> 3.14 Gm

试试最简单、可能也是最有效的方法怎么样? normalize()方法删除所有最右边的尾随零。

from decimal import Decimal

print (Decimal('0.001000').normalize())
# Result: 0.001

适用于Python 2和Python 3。

——更新——

正如@BobStein-VisiBone指出的那样,唯一的问题是,像10,100,1000这样的数字……将以指数形式显示。使用下面的函数可以很容易地解决这个问题:

from decimal import Decimal


def format_float(f):
    d = Decimal(str(f));
    return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

我呢,我会用('%f' % x).rstrip('0').rstrip('.')——保证定点格式,而不是科学符号,等等。是的,不像%g那么流畅和优雅,但是,它是有效的(而且我不知道如何强迫%g永远不使用科学符号;-)。

处理%f和你应该放

% .2f

,地点: .2f == .00浮动。

例子:

价格:%。2f" %价格[产品]

输出:

价格:1.50