Formatting number (s) into Currency strings manually is tall order. It becomes murkier when you have several lines to convert. It can also be termed as the conversion of a numerical number to a string or code. Several currencies can use a coma for the separation of every 3 Digits, whereas, others use a certain period to do the same. However, not all of them, others are exactly opposite of the two. To achieve fast and efficient formatting, an automated function is required. In this article, we will be showing you how to use Python to Format Currency strings using numbers. We will be using several methods to illustrate Python Format Currency-Code Example.
The following methods or modules facilitate the conversion of Numbers to Currency format or strings, the Locale, Babel, and str. We will see how the three works with Python.
Using Locale Module
The module is a component in python; however, it cannot operate alone. For this article, we will use Babel, whcih has to be installed on the python Application. An inbuilt Locale in the python software enables the developers or users to customize their APPs. Therefore, the issue of where the software will be used in the universe does not matter. A written Codebase enables it to adjust in whatever region. To use the Locale, the user will need to do some settings as shown below.
import locale
# To use default settings, set locale to None or leave second argument blank.
print(locale.setlocale(locale.LC_ALL, ''))
# To use a specific locale (Great Britian's locale in this case)
print(locale.setlocale(locale.LC_ALL, 'en_GB'))
The code will lead to,
English_United States.1252
en_GB.
For available Locales List you can follow the process below.
# For the Windows operating system
for lang in locale.windows_locale.values():
print(lang)
# For other operating systems
for lang in locale.locale_alias.values():
print(lang)
You can run the outcome and it will lead to,
en_GB
af_ZA
sq_AL
gsw_FR
am_ET
ar_SA
ar_IQ
ar_EG
ar_LY
ar_DZ
...
You can use the Locale set that suits your taste to create Number strings and thereafter run the resulting code to give you an output with the Python Format Currency output.
locale.setlocale(locale.LC_ALL, '')
# If you'd like groupings - set grouping to True, else set it to false or leave it out completely
print(locale.currency(12345.67, grouping=True))
print(locale.currency(12345.67))
Leading to,
$12,345.67
$12345.67
Python Format Currency, using Str. String
The str. string is the most straightforward and applicable method. After putting the Number string, it will bring the below output.
number_string = 340020.8
# This portion is responsible for grouping the number
number_commas_only = "{:,}".format(number_string)
print(number_commas_only)
# To ensure we have two decimal places
number_two_decimal = "{:.2f}".format(number_string)
print(number_two_decimal)
# Both combined along with the currency symbol(in this case $)
currency_string = "${:,.2f}".format(number_string)
print(currency_string)
Once we run the above outcome, we get the output below.
340,020.8
340020.80
$340,020.80
Using Babel
It is a user-friendly method; however, it is not known by many users or developers. It incorporates currency formatting, Number, and other tasks. The Format adjusts automatically in whatever region it is being used. We will install it using pip and run the command as hereunder. Thereafter, you can get the Formatted Currency as shown in the below illustrations.
$ pip install Babel
...
Successfully installed Babel-2.9.0
The outcome
import babel.numbers
number_string = 340020.8
# The three needed arguements are the number, currency and locale
babel.numbers.format_currency(number_string, "USD", locale='en_US')
Afterwards we run the code and get the outcome below.
$340,020.80
For Full list of Babel Locales, we use the following data,
avail_loc = babel.localedata.locale_identifiers()
print(avail_loc)
The data gives us to the below code:
['af', 'af_NA', 'af_ZA', 'agq', 'agq_CM', 'ak', 'ak_GH', 'am', 'am_ET',...]
Next We will Format Number Strings to Currency
Sometimes the data could be large, a sentence or complicated. Where there is no real numerical numbers or input from the source, the re Module can be used to sift through different inputs to get values that are numerical then format them. We will still use the above formats to format the currency. We import the three as in the below set up.
import re
import locale
import babel.numbers
locale.setlocale(locale.LC_ALL, 'en_US')
The outcome gives the Number string-matching pattern.
pattern r = '\d+(\.\d{1,2})?'
For String, Variable Message like this,
“Our current budget is 180000, we’ll need 25000.67 to cover rent, then 23400.4 for food.” the working is as follows.
# re.sub() is used to substitute substrings that match a certain pattern
# with another string, in our case the return value of a lambda function
# which will return a matching currency string.
new_message_locale = re.sub(
pattern, lambda x: locale.currency(float(x.group()), grouping=True), message
)
new_message_str = re.sub(
pattern, lambda x: "${:,.2f}".format(float(x.group())), message
)
new_message_babel = re.sub(
pattern,
lambda x: babel.numbers.format_currency(float(x.group()), "USD", locale="en_US"),
message,
Let us see the outcome from the three methods
print(message)
print(new_message_locale)
print(new_message_str)
print(new_message_babel)
Our current budget is 180000, we'll need 25000.67 to cover rent, then 23400.4 for food.
Our current budget is $180,000.00, we'll need $25,000.67 to cover rent, then $23,400.40 for food.
Our current budget is $180,000.00, we'll need $25,000.67 to cover rent, then $23,400.40 for food.
Our current budget is $180,000.00, we'll need $25,000.67 to cover rent, then $23,400.40 for food.
Whatever the format one uses, it is bound to have limitations. However, the length of the code or script depends on the method used. The code cannot differentiate the formatting of the number Strings. However, this should not worry you because you can customize it easily to suit your use and need. It is important to note that whichever format or method one uses, the version of the Python matters. To get the latest and more detailed outcomes, the user should use the latest Python version.
We do hope that the article has been able to assist you to learn and understand how to format currency Strings into numbers and vice versa. In summary, we also combined the above methods and the regular method of Python to come up with several use cases. We do hope from now on, you will be able to use Python Format Currency in formatting number (s) into Currency strings easily and conveniently. You do not have to spend all your time in performing the above tasks manually, use the above methods and thank us later.