HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to print a number using commas as thousands separators

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howseparatorsusingcommasprintnumberthousands

Problem

How do I print an integer with commas as thousands separators?

1234567   ⟶   1,234,567


It does not need to be locale-specific to decide between periods and commas.

Solution

Locale-agnostic: use _ as the thousand separator

f'{value:_}'          # For Python ≥3.6


Note 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_567


English style: use , as the thousand separator

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}'          # For Python ≥3.6


Locale-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.6


Reference

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.6
1234567 ⟶ 1_234_567
'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}'          # For Python ≥3.6
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.6

Context

Stack Overflow Q#1823058, score: 2569

Revisions (0)

No revisions yet.