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?
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