How to format a floating number to fixed width in Python

后端 未结 8 1066
长发绾君心
长发绾君心 2020-11-22 10:26

How do I format a floating number to a fixed width with the following requirements:

  1. Leading zero if n < 1
  2. Add trailing decimal zero(s) to fill up f
8条回答
  •  时光取名叫无心
    2020-11-22 11:01

    It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings:

    numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
    
    for number in numbers:
        print(f'{number:9.4f}')
    

    Prints:

      23.2300
       0.1233
       1.0000
       4.2230
    9887.2000
    

提交回复
热议问题