Skip to main content
 首页 » 编程设计

Python:用零填充 float

2025年05月04日9insus

如何用零填充双数到指定长度?

printf "{:.3}".format(0.12) # Doesn't pad 

我想得到

0.120 

请您参考如下方法:

3 之后需要一个 f:

In [19]: "{:.3f}".format(0.12) 
Out[19]: '0.120' 

对于 float ,如果您未指定任何类型,则默认使用 'g'。

In [27]: "{:.20}".format(0.12) 
Out[27]: '0.11999999999999999556' 
 
In [28]: "{:.20g}".format(0.12) 
Out[28]: '0.11999999999999999556' 

文档 here .