# View the original blog post at http://queirozf.com/entries/python-number-formatting-examples

## round to 2 decimal places

``````

In [1]:

'{:.2f}'.format(8.499)

``````
``````

Out[1]:

'8.50'

``````

## format float as percentage

``````

In [2]:

'{:.2f}%'.format(10.12345)

``````
``````

Out[2]:

'10.12%'

``````

## truncate to at most 2 decimal places

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

``````

In [3]:

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 [4]:

truncate(8.499,decimal_places=2)

``````
``````

Out[4]:

'8.49'

``````
``````

In [5]:

truncate(8.49,decimal_places=2)

``````
``````

Out[5]:

'8.49'

``````
``````

In [6]:

truncate(8.4,decimal_places=2)

``````
``````

Out[6]:

'8.4'

``````
``````

In [7]:

truncate(8,decimal_places=2)

``````
``````

Out[7]:

'8'

``````

``````

In [8]:

# make the total string size AT LEAST 9 (including digits and points), fill with zeros to the left
'{:0>9}'.format(3.499)

``````
``````

Out[8]:

'00003.499'

``````
``````

In [9]:

# make the total string size AT LEAST 2 (all included), fill with zeros to the left
'{:0>2}'.format(3)

``````
``````

Out[9]:

'03'

``````

``````

In [10]:

# make the total string size AT LEAST 11 (including digits and points), fill with zeros to the RIGHT
'{:<011}'.format(3.499)

``````
``````

Out[10]:

'3.499000000'

``````

## separators

``````

In [11]:

"{:,}".format(100000)

``````
``````

Out[11]:

'100,000'

``````