我如何格式化一个浮点数,使它不包含尾随零?换句话说,我希望得到的字符串尽可能短。
例如:
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"
当前回答
试试最简单、可能也是最有效的方法怎么样? 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()
其他回答
你可以使用%g来实现:
'%g'%(3.140)
或者,Python≥2.6:
'{0:g}'.format(3.140)
或者,Python≥3.6:
f'{3.140:g}'
格式:g cause (among other things)
不重要的后面的零[是] 从意义上移除,和 如果有,小数点也会被移除 后面没有剩余数字。
你可以简单地使用format()来实现:
格式(3.140,'.10g'),其中10是您想要的精度。
你可以像这样使用max():
打印(max (int (x), x)
如果你想要一些既适用于数字输入又适用于字符串输入的东西(感谢@mike-placentra的bug搜索):
def num(s):
""" 3.0 -> 3, 3.001000 -> 3.001 otherwise return s """
s = str(s)
try:
int(float(s))
if '.' not in s:
s += '.0'
return s.rstrip('0').rstrip('.')
except ValueError:
return s
>>> for n in [3, 3., 3.0, 3.1, 3.14, 3.140, 3.001000, 30 ]: print(num(n))
...
3
3
3
3.1
3.14
3.14
3.001
30
>>> for n in [3, 3., 3.0, 3.1, 3.14, 3.140, 3.001000, 30 ]: print(num(str(n)))
...
3
3
3
3.1
3.14
3.14
3.001
30
我呢,我会用('%f' % x).rstrip('0').rstrip('.')——保证定点格式,而不是科学符号,等等。是的,不像%g那么流畅和优雅,但是,它是有效的(而且我不知道如何强迫%g永远不使用科学符号;-)。