
PYTHON — Format Currency Exercise in Python
Computers are good at following instructions, but not at reading your mind. — Donald Knuth
Formatting Currency in Python
In this exercise, you will learn how to format an integer number as a currency amount in Python. This includes adding the currency symbol, grouping thousands with commas, and ensuring that the amount always displays two decimal places, even when there are no cents.
Code Implementation
You can achieve the desired formatting using the locale module in Python. First, you'll need to import the module:
import localeNext, set the locale to the user’s default settings:
locale.setlocale(locale.LC_ALL, '')Now you can use the currency function to format the number as currency:
formatted_currency = locale.currency(5000, grouping=True)
print(formatted_currency)In the above code snippet, locale.currency takes two arguments: the currency value (in this case, 5000) and a boolean indicating whether to use the grouping (thousands separator) feature.
The output of the print statement will be the formatted currency:
$5,000.00Summary
By using the locale module in Python, you can easily format integer numbers as currency amounts with the appropriate symbol, comma grouping, and decimal places. This is a simple yet effective way to display currency values in your Python applications.
Now that you’ve learned how to format currency in Python, you can apply this knowledge to enhance the user experience when working with financial data or monetary calculations in your programs.






