如何在python中格式化浮点数?

Man*_*nil 6 python format

我想用小数点后两位数来格式化我的浮点数。

>>> x =5.0
>>> y=float("{:0.2f}".format(x))
>>> y
5.0
Run Code Online (Sandbox Code Playgroud)

我想要这种格式的输出:

5.00
Run Code Online (Sandbox Code Playgroud)

Sal*_*man 6

对于较新版本的 python,您可以使用:

x = 5.0
print(f' x: {x:.2f}')
Run Code Online (Sandbox Code Playgroud)

输出将是:

x: 5.00
Run Code Online (Sandbox Code Playgroud)

有关此样式的更多信息,请参阅:f-string


Nis*_*ede 3

你可以这样做

In [11]: x = 5

In [12]: print("%.2f" % x)
5.00

In [13]:
Run Code Online (Sandbox Code Playgroud)