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:
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>
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!