To add commas to numbers in Python, the easiest way is using the Python string formatting function format() with “{:, }”.
amt = 3210765.12
amt2 = 1234.56
print("{:,}".format(amt))
print("{:,}".format(amt2))
#Output:
3,210,765.12
1,234.56
When working with numbers in Python, many times you need to format those numbers a certain way.
One such situation is if you want to add commas to numbers in your program or application.
To add commas to numbers in Python, the easiest way is using the Python string formatting function format() with “{:, }”.
Below is a simple example showing you how to add commas to numbers with format() in Python.
amt = 3210765.12
amt2 = 1234.56
print("{:,}".format(amt))
print("{:,}".format(amt2))
#Output:
3,210,765.12
1,234.56
Dollar Format with Commas for Numbers in the Thousands or Higher in Python
If you have an application or program which is working with numbers representing money, you can easily use format() to create a dollar format.
For example, if you want to include commas for numbers over 1,000 in your dollar format, then you can use “${:0,.2f}” following to format numbers as dollars.
Below shows a few examples of how you can add commas to your dollar format in Python.
amt = 12.34
amt2 = 1234.56
print("${:0,.2f}".format(amt))
print("${:0,.2f}".format(amt2))
#Output:
$12.34
$1,234.56
Hopefully this article has been useful for you to learn how to add commas to numbers in Python.