How to format a floating number to fixed width in Python

后端 未结 8 1071
长发绾君心
长发绾君心 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 10:59

    See Python 3.x format string syntax:

    IDLE 3.5.1   
    numbers = ['23.23', '.1233', '1', '4.223', '9887.2']
    
    for x in numbers:  
        print('{0: >#016.4f}'. format(float(x)))  
    
         23.2300
          0.1233
          1.0000
          4.2230
       9887.2000
    

提交回复
热议问题