Python number formatting examples
Last updated:Table of Contents
- Format float as integer
- Round float to 2 decimal places
- Format float as percentage
- Truncate float at 2 decimal places
- Left padding with zeros
- Right padding with zeros
- Use commas as thousands separator
- Interpolate variable with f-strings
- ValueError: zero length field name in format
All examples assume Python 3+
See the difference between truncating and rounding a number
All examples can be viewed on this jupyter notebook
Format float as integer
In other words, round it up to the nearest integer and format:
print('{:.0f}'.format(8.0))
# >>> '8'
print('{:.0f}'.format(8.9))
# >>> '9'
Round float to 2 decimal places
print('{:.2f}'.format(5.39120))
# >>> '5.39'
Format float as percentage
Format a number as a percentage, with 2 decimal places
'{:.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'
Interpolate variable with f-strings
You can use any of the other formatting options with f-strings:
Example: truncate to 2 decimal places in f-string
num = 1.12745
formatted = f"{num:.2f}"
formatted
# >>> '1.13'
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:
# ValueError 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"