round to 2 decimal places

In [1]:
'{0:.2f}'.format(8.499)
Out[1]:
'8.50'

truncate to at most 2 decimal places

turn it into a string then replace everything after the second digit after the point

In [2]:
import re

def truncate(num,decimal_places):  
    dp = str(decimal_places)
    return re.sub(r'^(\d+\.\d{,'+re.escape(dp)+r'})\d*$',r'\1',str(num))
In [3]:
truncate(8.499,decimal_places=2)
Out[3]:
'8.49'
In [4]:
truncate(8.49,decimal_places=2)
Out[4]:
'8.49'
In [5]:
truncate(8.4,decimal_places=2)
Out[5]:
'8.4'
In [6]:
truncate(8,decimal_places=2)
Out[6]:
'8'

left padding with zeros

Here: make the full size equal to 9 (all included), fill with zeros to the left

In [7]:
'{0:0>9}'.format(3.499)
Out[7]:
'00003.499'

right padding with zeros

Here: make the full size equal to 11, fill with zeros to the right

In [8]:
'{0:<011}'.format(3.499)
Out[8]:
'3.499000000'