填充python浮动

填充python浮动,python,floating-point,zero,pad,Python,Floating Point,Zero,Pad,我想填充一些百分比值,这样在小数点前总是有3个单位。对于int,我可以使用“%03d”-是否有与float等效的值 “%.3f”在小数点后适用,但“%03f”不起作用。“%03.1f”适用(1可以是任何数字或空字符串): 请注意,字段宽度包括小数和小数。您也可以使用zfill str(3.3).zfill(5) '003.3' 或者,如果要使用.format: {:6.1f} ↑ ↑ | | # di

我想填充一些百分比值,这样在小数点前总是有3个单位。对于int,我可以使用“%03d”-是否有与float等效的值

“%.3f”在小数点后适用,但“%03f”不起作用。

“%03.1f”适用(1可以是任何数字或空字符串):


请注意,字段宽度包括小数和小数。

您也可以使用zfill

str(3.3).zfill(5)
'003.3'

或者,如果要使用
.format

              {:6.1f}
                ↑ ↑ 
                | |
# digits to pad | | # of decimal places to display
复制粘贴:
{:6.1f}

上面的6包括小数点左边的数字、小数标记和小数点右边的数字

用法示例:

'{:6.2f}'.format(4.3)
Out[1]: '  4.30'

f'{4.3:06.2f}'
Out[2]: '004.30'
举个简单的例子:

var3= 123.45678
print(
    f'rounded1    \t {var3:.1f} \n' 
    f'rounded2    \t {var3:.2f} \n' 
    f'zero_pad1   \t {var3:06.1f} \n'  #<-- important line
    f'zero_pad2   \t {var3:07.1f}\n'   #<-- important line
    f'scientific1 \t {var3:.1e}\n'
    f'scientific2 \t {var3:.2e}\n'
)

如果该值为负数,则前导“-”将消耗一个字段宽度计数-“%06.2f”%-3.3给出“-03.30”,因此,如果必须有3个数字,即使是负数,也必须在字段宽度上再添加一个数字。可以使用“”fieldwidth值执行此操作,并传递一个计算值:value=-3.3;打印“%0.2f”%(6+(值@PaulMcGuire的意思是这样的,但使用
格式
值=-3.3;打印“{t:0{format}.2f}”。格式(format=6+(值注意,这是要填充的总数字,包括小数点右侧的数字。这不仅仅是小数点左侧的数字。我花了太长的时间才弄明白为什么这不起作用
var3= 123.45678
print(
    f'rounded1    \t {var3:.1f} \n' 
    f'rounded2    \t {var3:.2f} \n' 
    f'zero_pad1   \t {var3:06.1f} \n'  #<-- important line
    f'zero_pad2   \t {var3:07.1f}\n'   #<-- important line
    f'scientific1 \t {var3:.1e}\n'
    f'scientific2 \t {var3:.2e}\n'
)
rounded1         123.5 
rounded2         123.46 
zero_pad1        0123.5 
zero_pad2        00123.5
scientific1      1.2e+02
scientific2      1.23e+02