Home >Backend Development >Python Tutorial >How to Format Numbers with Thousands Separators in Python?

How to Format Numbers with Thousands Separators in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 00:38:10497browse

How to Format Numbers with Thousands Separators in Python?

How to Print a Number with Commas as Thousands Separators

Formatting large numbers with thousands separators can enhance their readability. Here are several approaches to achieve this in Python:

Locale-Agnostic Solution

For a universal approach, regardless of locale, you can utilize an underscore as the separator:

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

However, this method will always employ the underscore, regardless of the current locale.

English Style

If you prefer the traditional English formatting, you can use a comma as the separator:

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

Locale-Aware Solution

To adapt to the user's locale, you can implement the following steps:

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

This method will use the appropriate separator based on the user's locale.

Reference

According to the Format Specification Mini-Language:

  • The ',' option indicates a comma as the thousands separator.
  • The '_' option employs an underscore as the thousands separator for floating point and 'd' integer presentation types.
  • For 'b', 'o', 'x', and 'X' integer presentation types, underscores will be inserted every 4 digits.

The above is the detailed content of How to Format Numbers with Thousands Separators in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn