Pad python floats

让人想犯罪 __ 提交于 2019-11-29 16:06:33

问题


I want to pad some percentage values so that there are always 3 units before the decimal place. With ints I could use '%03d' - is there an equivalent for floats?

'%.3f' works for after the decimal place but '%03f' does nothing.


回答1:


'%03.1f' works (1 could be any number, or empty string):

>>> "%06.2f"%3.3
'003.30'

>>> "%04.f"%3.2
'0003'

Note that the field width includes the decimal and fractional digits.




回答2:


Alternatively, if you want to use .format:

              {:6.1f}
                ↑ ↑ 
                | |
# digits to pad | | # of decimal places to display

Copypasta: {:6.1f}

Example of usage:

'Num: {:6.1f}'.format(number)



回答3:


You could use zfill as well,.

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



回答4:


A short example:

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'
)

Gives the output

rounded1         123.5 
rounded2         123.46 
zero_pad1        0123.5 
zero_pad2        00123.5
scientific1      1.2e+02
scientific2      1.23e+02


来源:https://stackoverflow.com/questions/1424638/pad-python-floats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!