snippetpythonCriticalCanonical
How to print a number using commas as thousands separators
Viewed 0 times
howseparatorsusingcommasprintnumberthousands
Problem
How do I print an integer with commas as thousands separators?
It does not need to be locale-specific to decide between periods and commas.
1234567 ⟶ 1,234,567It does not need to be locale-specific to decide between periods and commas.
Solution
Locale-agnostic: use
Note that this will NOT format in the user's current locale and will always use
English style: use
Locale-aware
Reference
Per Format Specification Mini-Language,
The
and:
The
_ as the thousand separatorf'{value:_}' # For Python ≥3.6Note that this will NOT format in the user's current locale and will always use
_ as the thousand separator, so for example:1234567 ⟶ 1_234_567English style: use
, as the thousand separator'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6Locale-aware
import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6Reference
Per Format Specification Mini-Language,
The
',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.and:
The
'_' option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits.Code Snippets
f'{value:_}' # For Python ≥3.61234567 ⟶ 1_234_567'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6Context
Stack Overflow Q#1823058, score: 2569
Revisions (0)
No revisions yet.