Format numbers as currency strings using str.format()

Another way to format numbers as currency strings is to the use the str.format() method with the format specifier for currency.

# Format a number as a currency string using str.format()
currency_string = '${:,.2f}'.format(1234.56)
  • ${:,.2f} – A format specifier for currency strings:
  • $ – The currency symbol.
  • :, – Thousands separator.
  • .2f – Floating-point precision.

Below is the implementation for formatting numbers as currency strings using str.format() in Python:

Python
# Format a number as a currency string using the str.format()
GFG = '${:,.2f}'.format(1234.56)
print(GFG)

Output
$1,234.56

In this code snippet, the str.format() method is used to the format the number 1234.56 as a currency string with the two decimal places and commas for the thousands separators prefixed with the dollar sign (β€˜$’). Here’s a breakdown of the formatting:

  • β€˜{:,.2f}’ is a format specifier that specifies how the number should be formatted:
  • β€˜,’ enables the use of the commas as the thousands separator.
  • β€˜.2f’ specifies that the number should be formatted as the floating-point number with the two decimal places.
  • β€˜{:,.2f}’.format(1234.56) formats the number 1234.56 according to format specifier and returns the formatted string β€˜$1,234.56’.
  • Finally, the formatted string β€˜$1,234.56’ is assigned to the variable GFG in which is then printed to console.

How to format numbers as currency strings in Python

Formatting numbers as currency strings in Python is a common requirement especially in the applications involving financial data. Formatting numbers as currency strings in Python involves presenting numeric values in the standardized currency format typically including the currency symbol, thousands separators and the number of the decimal places. Python provides the several ways to the format numbers as currency strings including the locale module and str.format() method.

Similar Reads

Format numbers as currency strings using the locale Module:

The locale module provides a way to the format numbers as currency strings according to user’s locale settings. It uses the locale.currency() function for the formatting....

Format numbers as currency strings using str.format():

Another way to format numbers as currency strings is to the use the str.format() method with the format specifier for currency....