Python number formatting examples

Last updated:
Table of Contents

All examples assume Python 2.7+

See the difference between truncating and rounding a number

All examples can be viewed on this jupyter notebook

Round float to 2 decimal places

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

Format float as percentage

Format a number as a percentage, with rounding as above:

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

Truncate float at 2 decimal places

View the full code for a generalized version on this notebook

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

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

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

Right padding with zeros

Example make the full size equal to 11, filling with zeros to the right:

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

Use commas as thousands separator

"{:,}".format(100000)
# >>> '100,000'

Troubleshooting: ValueError: zero length field name in format

In some Python versions such as 2.6 and 3.0, you must specify positional indexes in the format string:

# ERROR in python 2.6 and 3.0
a=1
b=2
"{}-{}".format(a,b)

# NO ERROR in any python version
"{0}-{1}".format(a,b)
# >>> "1-2"

References

Dialogue & Discussion