Padding Numbers and Truncating them in Python

185 views Asked by At

Im currently writing a program in python and i need to be able to truncate the number after 2 decimal places and align it in a table. However, i am unsure how to truncate AND pad my output. Here is the code i want to alter that currently has truncation.

print(month_count,'\t','\t',monthly_payment,'\t','\t',"%.2f" % '%d' % interest_amount,'\t','\t',"%.2f" % loan)
1

There are 1 answers

0
CT Zhu On

You might want to use .format() for both truncation and alignment:

In [6]: '{:>10.2f}'.format(1000.00001)
Out[6]: '   1000.00'

>10 part means right adjusted with total of 10 characters. .2f means keep only 2 decimal places.

See https://pyformat.info/ for more