How to format a floating number to fixed width in Python

后端 未结 8 1069
长发绾君心
长发绾君心 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:07

    This will print 76.66:

    print("Number: ", f"{76.663254: .2f}")
    
    0 讨论(0)
  • 2020-11-22 11:08

    You can also left pad with zeros. For example if you want number to have 9 characters length, left padded with zeros use:

    print('{:09.3f}'.format(number))

    Thus, if number = 4.656, the output is: 00004.656

    For your example the output will look like this:

    numbers  = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
    for x in numbers: 
        print('{:010.4f}'.format(x))
    

    prints:

    00023.2300
    00000.1233
    00001.0000
    00004.2230
    09887.2000
    

    One example where this may be useful is when you want to properly list filenames in alphabetical order. I noticed in some linux systems, the number is: 1,10,11,..2,20,21,...

    Thus if you want to enforce the necessary numeric order in filenames, you need to left pad with the appropriate number of zeros.

    0 讨论(0)
提交回复
热议问题