Formatting Numbers So They Align On Decimal Point

mcu picture mcu · Sep 27, 2015 · Viewed 11.7k times · Source

In Python, I need to format numbers so they align on the decimal point, like so:

  4.8
 49.723
456.781
-72.18
  5
 13

Is there a straighforward way to do this?

Answer

artomason picture artomason · Oct 4, 2018

If you know the precision (digits after the decimal point) that you need, and you don't mind having some trailing zeros when whole numbers are used, you could use the new f-string in Python 3.6 (PEP498):

numbers = [4.8, 49.723, 456.781, -72.18, 5, 13]

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

Prints:

  4.8000
 49.7230
456.7810
-72.1800
  5.0000
 13.0000