How to format a number with commas?
To format a number with commas, use f-strings in Python 3.6+ or the format() function in older versions of Python 3.
To clarify, the formatting will add a comma for every thousand as shown below.
5000 is formatted to 5,000
50000 is formatted to 50,000
500000 is formatted to 500,000
5000000 is formatted to 5,000,000
format number with commas using f-strings
To format a number with commas in Python 3.6 and above use f-strings as shown below.
# PYTHON 3.6 AND ABOVE
# format a number with commas using f-strings
myNumber = 1000000.11
print(f"{myNumber:,}")
The f-string replaces myNumber with the actual value. The number is printed with comma-separated digits.
1,000,000.11
format number with commas (older Python3)
For older versions of Python 3 (below 3.6) f-strings are not available, use the format() function instead.
# format a number with commas using the format() function
myNumber = 1000000.11
print(format(myNumber, ","))
The format() function is used to format the number with commas. The result is returned and printed.
1,000,000.11
define own function
To format numbers with commas, define your own function as shown below.
# define your own function to format numbers with commas
def add_commas(number):
return ("{:,}".format(number))
myNumber = 1000000.11
# call the defined function
formattedNumber = add_commas(myNumber)
# print the formatted number
print(formattedNumber)
The add_commas function is defined format the number with commas.
Then the add_commas() function is called and finally the result is printed.
1,000,000.11
format number with commas and round
The format() function allows us to format a number with commas and round the result at the same time. The decimal places can be specified as shown below.
# format number with commas and round
myNumber = 1000000.11
# round to 1 decimal places
rounded = "{:,.1f}".format(myNumber)
# round to integer
myInteger = "{:,.0f}".format(myNumber)
# print values
print(rounded)
print(myInteger)
The first value is formatted with commas and rounded to 1 decimal place.
The second value is formatted with commas and rounded to an integer.
1,000,000.1
1,000,000