Home > Backend Development > Python Tutorial > How can I format currency values in Python according to local conventions?

How can I format currency values in Python according to local conventions?

Patricia Arquette
Release: 2024-11-01 02:51:02
Original
699 people have browsed it

How can I format currency values in Python according to local conventions?

Currency Formatting in Python

When working with numbers representing currency values, it is often necessary to format them in a way that reflects the local currency conventions. For example, you may want to format a number like 188518982.18 as £188,518,982.18.

Solution using the locale module

Python's locale module provides built-in support for currency formatting. To use it, follow these steps:

  1. Import the locale module.
  2. Set the locale to the desired location to establish the currency format.
  3. Use the currency() function to format the number.

Example

The following code snippet demonstrates how to format a number as a British currency:

<code class="python">import locale

# Set the locale to British English
locale.setlocale(locale.LC_ALL, 'en_GB')

# Format the number as British currency
formatted_number = locale.currency(188518982.18)

print(formatted_number)  # Output: £188,518,982.18

# Enable grouping of digits (adds commas as separators)
formatted_number = locale.currency(188518982.18, grouping=True)

print(formatted_number)  # Output: £188,518,982.18</code>
Copy after login

By incorporating these steps, you can easily format numbers as currency values in Python, ensuring that they adhere to the desired locale conventions.

The above is the detailed content of How can I format currency values in Python according to local conventions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template