How to Format Number as Currency String in Python

Introduction

Having to manually format a number as a currency string can be a tedious process. You may have just a few lines of modifications to make, however, when we need to do a fair bit of conversions, it becomes very tedious.

The first step to automating these kinds of tasks will require a function. In this article, we'll be going over a few methods you can use to format numbers as currency strings in Python.

Methods for Formatting Numbers

We'll be going over three alternate libraries and functions which allow us to convert numbers into currency strings:

  • The locale module.
  • The Babel module.
  • The str.format() function.

The locale module is already included in Python, though, we'll have to install Babel to use it.

Format Number as Currency String with Locale

The locale module comes already preinstalled with your version of Python.

This package allows developers to localize their applications. Meaning they don't have to know in which region their software will be run, they can just write a universal codebase which will dynamically change depending on the region of use.

Initializing the Locale

To begin using the locale module you first need to set the locale:

import locale 

# To use default settings, set locale to None or leave the second argument blank.
print(locale.setlocale(locale.LC_ALL, ''))

# To use a specific locale (Great Britain's locale in this case)
print(locale.setlocale(locale.LC_ALL, 'en_GB'))

The code above will produce the following output:

English_United States.1252
en_GB

To get the list of available locales, you can look it up on MS-LCID. Alternatively, you can print it out:

# 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)

Running any of the above variants will yield something similar to:

en_GB
af_ZA
sq_AL
gsw_FR
am_ET
ar_SA
ar_IQ
ar_EG
ar_LY
ar_DZ
...

Formatting Numbers with Locale

With your preferred locale set, you can easily format number strings:

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))

Running the code above we get the following output:

$12,345.67
$12345.67

Using the str.format() method

The next method we'll be covering is the str.format() method, which has the advantage of being the most straightforward one:

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)

Running the code above we get the following output:

340,020.8
340020.80
$340,020.80

Though, this approach is hard-coded, unlike the previous one, which you can use to localize the formatting dynamically.

Format Number as Currency String with Babel

Using Babel is perhaps one of the lesser known methods, however it's very user-friendly and intuitive. It comes with number and currency formatting as well as other internationalizing tasks.

Unlike Python's locale module, you don't have to worry about making adjustments on a global scale.

To install Babel via pip, run the following command:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

$ pip install Babel
...
Successfully installed Babel-2.9.0

Once installed, to achieve the same results as the two other methods listed above, you can simply call format_currency() on a string:

import babel.numbers
number_string = 340020.8

# The three needed arguments are the number, currency and locale
babel.numbers.format_currency(number_string, "USD", locale='en_US')

Running the code above we get the following output:

$340,020.80

To get the full list of locales available:

avail_loc = babel.localedata.locale_identifiers()
print(avail_loc)

Which looks something like this:

['af', 'af_NA', 'af_ZA', 'agq', 'agq_CM', 'ak', 'ak_GH', 'am', 'am_ET',...]

Searching For Numbers in Strings and Formatting as Currency

Sometimes, you don't work with direct numerical input, such as the input from a user. You might be working with a sentence, or a larger, unclean corpus. We can use the re module to filter through different types of input, find numerical values and format them.

Let's use all three of the approaches above to format the currency in a sentence:

import re
import locale
import babel.numbers
locale.setlocale(locale.LC_ALL, 'en_US')

Next we come up with the regex pattern needed to match the number strings:

 # This pattern is used to match any number string
 pattern = r'\d+(\.\d{1,2})?'

Next we apply the three methods we've learned to the string variable message:

message = "Our current budget is 180000, we'll need 25000.67 to cover rent, then 23400.4 for food."

# 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's compare the original output with the output gotten from all 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.

Depending on the method you prefer, the length of this script can be reduced. There are certain limitations as you may have noticed.

The script as it is, is unable to differentiate between number strings you'd like to format. However, it can be changed easily depending on your needs and use cases.

Conclusion

In this article we took a look at a couple of ways of converting numbers into proper currency strings. We've covered the str.format() method, as well as the locale and babel modules.

Finally we combined these methods with Python's regular expression module to achieve a wider range of uses. In the end I hope you were able to learn something new from all this that can help save you time.

Last Updated: February 24th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms