hobbes3 hobbes3 - 5 months ago 16
Python Question

How to format a floating number to fixed width in Python

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 fixed width

  3. Truncate decimal digits past fixed width

  4. Align all decimal points



For example:

% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
print formatter.format(number)


The output would be like

23.2300
0.1233
1.0000
4.2230
9887.2000

Answer
for x in numbers:
    print "{:10.4f}".format(x)

prints

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000
Comments