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

例如:

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

当前回答

“(5g)。”format (x)

我用这个来格式化浮点到尾零。

其他回答

你可以像这样使用max():

打印(max (int (x), x)

如果你能接受3个。3.0以“3.0”的形式出现,这是一种非常简单的方法,从浮点数表示中右移零:

print("%s"%3.140)

(感谢@ellimilial指出了例外情况)

对于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,例如'%.99g'。 它将以定点符号打印任何相当大的数字。

编辑:它不起作用

>>> '%.99g' % 0.0000001
'9.99999999999999954748111825886258685613938723690807819366455078125e-08'

使用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