Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print number with commas as 1000 separators in Python
Numbers with three or more digits often need to be displayed with commas for better readability, especially in accounting and finance applications. Python provides several methods to format numbers with commas as thousand separators.
Using f-strings (Python 3.6+)
The most modern approach uses f-string formatting with the comma specifier ?
# Format integers with commas
num1 = 1445
num2 = 140045
num3 = 5000000
print(f'{num1:,}')
print(f'{num2:,}')
print(f'{num3:,}')
1,445 140,045 5,000,000
Formatting Float Numbers
For floating-point numbers, specify the decimal precision along with comma separation ?
# Format floats with commas and 2 decimal places
price1 = 3435.242563
price2 = 1234567.89
price3 = 999.5
print(f'{price1:,.2f}')
print(f'{price2:,.2f}')
print(f'{price3:,.2f}')
3,435.24 1,234,567.89 999.50
Using format() Method
The traditional format() method works similarly for older Python versions ?
# Using format() method
num = 2500000
price = 12345.678
print("{:,}".format(num))
print("{:,.2f}".format(price))
2,500,000 12,345.68
Using locale Module
For locale-specific formatting based on system settings ?
import locale
# Set locale (use system default)
locale.setlocale(locale.LC_ALL, '')
num = 1234567.89
formatted = locale.format_string("%.2f", num, grouping=True)
print(formatted)
1,234,567.89
Format Specifiers
| Specifier | Purpose | Example |
|---|---|---|
:, |
Add commas to integers |
f'{1000:,}' ? 1,000 |
:,.2f |
Add commas with 2 decimal places |
f'{1000.5:,.2f}' ? 1,000.50 |
:,.0f |
Add commas, no decimals |
f'{1000.9:,.0f}' ? 1,001 |
Conclusion
Use f-strings with {num:,} for integers and {num:,.2f} for floats to add comma separators. F-strings provide the most readable and efficient solution for number formatting in modern Python.
