我如何格式化一个浮点数,使它不包含尾随零?换句话说,我希望得到的字符串尽可能短。
例如:
3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"
我如何格式化一个浮点数,使它不包含尾随零?换句话说,我希望得到的字符串尽可能短。
例如:
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)
不重要的后面的零[是] 从意义上移除,和 如果有,小数点也会被移除 后面没有剩余数字。
这里有一个对我有用的解决办法。它混合了PolyMesh的解决方案和使用新的.format()语法。
for num in 3, 3., 3.0, 3.1, 3.14, 3.140:
print('{0:.2f}'.format(num).rstrip('0').rstrip('.'))
输出:
3
3
3
3.1
3.14
3.14
你可以像这样使用max():
打印(max (int (x), x)
使用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
以下是答案:
import numpy
num1 = 3.1400
num2 = 3.000
numpy.format_float_positional(num1, 3, trim='-')
numpy.format_float_positional(num2, 3, trim='-')
输出“3.14”和“3”
Trim ='-'删除后面的0和小数。