Python number formatting examples

Last updated:

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Difference between truncating and rounding a number

View notebook here

Round float to 2 decimal places

print('{:.2f}'.format(5.39120))
>> '5.40'

Truncate float at 2 decimal places

This is just one way to do it. There probably are others.

This will drop digits after the second decimal place (if there are any).

import re

# see the notebook for a generalized version
def truncate(num):
    return re.sub(r'^(\d+\.\d{,2})\d*$',r'\1',str(num))

truncate(8.499)
>> '8.49'

truncate(8.49)
>> '8.49'

truncate(8.4)
>> '8.4'

truncate('8.0')
>> '8.0'

truncate(8)
>> '8'

Left padding with zeros

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

'{0:0>9}'.format(3.499)
>> '00003.499'

Right padding with zeros

E.g. make the full size equal to 11, fill with zeros to the right:

'{0:<011}'.format(3.499)
>> '3.499000000'

References

Dialogue & Discussion