Cómo formatear un número flotante a ancho fijo en Python


Cómo formateo un número flotante a un ancho fijo con los siguientes requisitos:

  1. Cero inicial si n
  2. Agregue cero(s) decimal (s) final (es) para completar el ancho fijo
  3. Trunca los dígitos decimales después de la anchura fija
  4. Alinear todos los puntos decimales

Por ejemplo:

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

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

La salida sería como

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000
Author: hobbes3, 2012-01-17

5 answers

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

Imprime

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000
 340
Author: Sven Marnach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-16 20:10:38

En python3 las siguientes obras:

>>> v=10.4
>>> print('% 6.2f' % v)
  10.40
>>> print('% 12.1f' % v)
        10.4
>>> print('%012.1f' % v)
0000000010.4
 25
Author: Scott Roberts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-26 04:19:30

Ver Python 3.x sintaxis de cadena de formato :

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
 6
Author: readyleader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-01 01:50:27

En Python 3.

GPA = 2.5
print(" %6.1f " % GPA)

6.1f significa que después de los puntos 1 dígitos muestran si imprime 2 dígitos después de los puntos solo debe %6.2f tal que %6.3f 3 dígitos imprimen después del punto.

 0
Author: Usman Zia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-19 07:19:33

Han sido algunos suyos desde que esto fue respondido, pero a partir de Python 3.6 ( PEP498 ) podría usar el nuevo f-strings:

numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print(f'{number:9.4f}')

Impresiones:

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000
 0
Author: artomason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 15:08:18