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

例如:

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

当前回答

你可以简单地使用format()来实现:

格式(3.140,'.10g'),其中10是您想要的精度。

其他回答

处理%f和你应该放

% .2f

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

例子:

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

输出:

价格:1.50

你可以使用%g来实现:

'%g'%(3.140)

或者,Python≥2.6:

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

或者,Python≥3.6:

f'{3.140:g}'

格式:g cause (among other things)

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

>>> str(a if a % 1 else int(a))

虽然格式化可能是最python的方式,但这里有一个使用more_itertools的替代解决方案。rstrip工具。

import more_itertools as mit


def fmt(num, pred=None):
    iterable = str(num)
    predicate = pred if pred is not None else lambda x: x in {".", "0"}
    return "".join(mit.rstrip(iterable, predicate))


assert fmt(3) == "3"
assert fmt(3.) == "3"
assert fmt(3.0) == "3"
assert fmt(3.1) == "3.1"
assert fmt(3.14) == "3.14"
assert fmt(3.140) == "3.14"
assert fmt(3.14000) == "3.14"
assert fmt("3,0", pred=lambda x: x in set(",0")) == "3"

数字被转换为字符串,该字符串去掉了满足谓词的尾随字符。函数定义fmt不是必需的,但是这里用它来测试断言,断言都通过了。注意:它适用于字符串输入并接受可选谓词。

另请参阅第三方库more_itertools的详细信息。

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

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