Python f-strings: Format Numbers and Currency

Published on: May 28, 2026
Reading time: 6 minutes
Como usar f-strings para formatar números e moedas em Python

Mastering data display is one of the most essential skills for any developer, and learning how to use Python f-strings to format numbers and currency is the fastest path to creating professional interfaces. Introduced in Python 3.6, f-strings (format string literals) revolutionized the way variables are embedded inside text. They do not just concatenate words — they offer a powerful formatting system capable of transforming raw numbers into monetary values, percentages, and aligned tables with very few lines of code.

Unlike older methods such as the % operator or the .format() method, f-strings let you write expressions directly inside curly braces {}. This makes the code much more readable and easier to maintain. Whether you are building a Python calculator or a complex financial system, understanding numeric formatting will prevent your reports from displaying confusing recurring decimals or misaligned values for the end user.

What are f-strings and why use them?

F-strings are identified by the f prefix before the opening quote. They are evaluated at runtime, which makes them faster than traditional methods. The big advantage of f-strings lies in their concise syntax. Instead of calling external rounding functions, you define the display mask directly inside the variable declaration.

Imagine you have a calculation result like 1234.5678 and need to display it as a dollar value. Without proper formatting, Python would show all decimal places. With f-strings, you solve this instantly, ensuring a polished and professional user experience and avoiding the common beginner mistakes in Python that tend to pollute the console with raw data.

How to format decimal places with f-strings

Controlling decimal places is the most frequent need in programming projects. To limit the number of digits after the decimal point, use the syntax :{total_places}f. For example, to show only two decimal places, use :.2f. The “f” indicates a float in Python (floating point number).

Python
price = 49.9987
print(f"Adjusted price: $ {price:.2f}")
# Output: Adjusted price: $ 50.00

Python performs automatic rounding to the nearest value. If the third decimal place is 5 or greater, the preceding digit is incremented. This precision is vital for anyone working with data analysis, where the visual clarity of results determines the quality of a report or chart.

Formatting numbers with thousand separators

To make large values like salaries or populations readable, thousand separators are essential. In the international English standard, a comma is used as the separator. In Python, simply add a comma after the colon inside the curly braces. The result is immediately cleaner and easier to scan.

Python
revenue = 1500750.50
print(f"Revenue: {revenue:,.2f}")
# Output: Revenue: 1,500,750.50

If you are developing a currency converter in Python, this formatting will be the visual differentiator of your software, giving users an immediately professional experience.

Alignment and padding of numbers

F-strings allow you to create perfectly aligned columns in the terminal without external libraries. This is useful for generating receipts or menus. You can define the total field width and the alignment direction using these symbols:

  • < : Align left.
  • > : Align right (default for numbers).
  • ^ : Center the content.
Python
item1 = "Keyboard"
price1 = 150.00
item2 = "Mouse"
price2 = 85.50

print(f"{item1:<15} | $ {price1:>8.2f}")
print(f"{item2:<15} | $ {price2:>8.2f}")

In the example above, 15 spaces are reserved for the item name and 8 for the price. This ensures the vertical bars and values stay aligned regardless of word length, something essential for building an interactive terminal menu.

Working with percentages easily

Converting decimals to percentages (e.g., 0.15 to 15%) is a daily task in automation scripts. Instead of multiplying by 100 and adding the symbol manually, use the % suffix inside the f-string. Python automatically multiplies the value by 100 and formats the decimal places as requested.

Python
success_rate = 0.8543
print(f"Accuracy rate: {success_rate:.1%}")
# Output: Accuracy rate: 85.4%

Formatting integers and zero-padding

Sometimes a number needs a fixed number of digits, such as in barcodes, user IDs, or dates. With f-strings, zero-padding is straightforward by specifying the desired fill. Working with integers in Python becomes much more organized when you standardize their display.

Python
day = 5
month = 9
year = 2023
print(f"Formatted date: {day:02d}/{month:02d}/{year}")
# Output: Formatted date: 05/09/2023

The 02d tells Python: “display an integer (d), ensure it is at least 2 characters wide, and fill with zero if necessary.” This is fundamental to avoid dates or codes with varying widths, which disrupts visual sorting.

Converting numeric bases (Hex, Binary, Octal)

For developers working with low-level code, electronics, or cryptography, converting a decimal number to other bases is a constant need. F-strings make this straightforward with the suffixes x (hexadecimal), b (binary), and o (octal).

According to the official Python documentation, f-strings are extensions of literal expressions that support these conversions natively.

Python
number = 255
print(f"Hex: {number:x}")  # ff
print(f"Bin: {number:b}")  # 11111111

To include the prefix (such as 0x or 0b), add the # symbol before the type: {number:#x}. This makes debugging much faster for those familiar with the essential Python commands.

Applying locale formatting for currency

Python uses the US standard by default. To convert “1,250.50” into locale-specific formats, use the locale module. This module adjusts the display settings according to the geographic region defined in the operating system.

Python
import locale

# Set to US English locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

value = 3500.75
formatted = locale.currency(value, grouping=True)
print(f"Balance: {formatted}")
# Output: Balance: $3,500.75

Combining the power of f-strings with the locale module is the definitive way to ensure your software is user-friendly across different regions. If you are building something that involves editing spreadsheets via Python, this formatting will ensure data inserted into cells follows the correct accounting standards.

F-string syntax quick reference

SyntaxPurposeExample
:.2fTwo decimal places12.35
:,Thousand separator1,000,000
:.0%Percentage without decimals85%
:0>5Zero-pad to total width 500042
:^10Center in 10 spaces Text

Best practices and caveats

Despite their power, f-strings should not be used for database queries or building dynamic URLs with data from unknown users, as they can open injection vulnerabilities. For those cases, use specific libraries or safe parameterized queries, as done when connecting Python to MySQL.

Also avoid placing complex logic inside the curly braces {}. Although Python allows it, this makes the code harder to read. If you need a large calculation before displaying, do it on a previous line and pass only the result to the f-string. Keeping Python indentation organized and expressions simple is the key to clean code.

Frequently Asked Questions

Can I use f-strings in Python 2.7?

No. F-strings were introduced in Python 3.6. For older versions, use the .format() method or the % operator.

How do I format a date using f-strings?

You can use datetime format specifiers directly: f"{now:%m/%d/%Y}" produces something like 12/25/2023.

How do I put quotes inside an f-string?

Use different quote types. If the f-string starts with double quotes, use single quotes inside the braces, or vice versa.

Is it possible to always round up?

F-strings use Python’s default rounding. If you always need to round up (ceiling), use the ceil function from the math module before formatting.

Are f-strings safe against SQL injection?

No. Never use f-strings to build SQL queries with user data. Use parameterized queries from database libraries such as sqlite3 or SQLAlchemy.

How do I display literal curly braces {} inside an f-string?

Double them: {{ }} will render as { }.

What is the performance difference between f-strings and .format()?

F-strings are considerably faster because Python processes them as low-level instructions, while .format() involves a method call and attribute lookup.

How do I format scientific notation (e.g., 1.2e+10)?

Use the :e or :E suffix inside the braces. For example: f"{value:e}".

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Logo do Python com as palavras global e local
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Variable Scope Explained Clearly

    Learn Python variable scope with clear examples of local, global, enclosing, built-in scope, LEGB rules, global, nonlocal, and common mistakes.

    Ler mais

    Tempo de leitura: 9 minutos
    28/05/2026
    Comparativo dos melhores cursos de Python para aprender programação
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    8 Best Python Courses for Beginners in 2026

    Compare the 8 best Python courses for beginners in 2026, including Academify, Alura, Udemy, Coursera, Codecademy, Harvard CS50, EBAC, and

    Ler mais

    Tempo de leitura: 7 minutos
    28/05/2026
    Uso do operador ternário em Python para condições rápidas
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Ternary Operator: Clean One-Line If

    Learn how Python ternary operators work, when to use one-line if expressions, how to avoid nested logic, and how to

    Ler mais

    Tempo de leitura: 8 minutos
    21/05/2026
    Logo lambda usado no Half-Life
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Lambda Functions Explained Clearly

    Learn Python lambda functions with clear examples, syntax, sorting, map, filter, closures, common mistakes, and when to prefer def.

    Ler mais

    Tempo de leitura: 8 minutos
    21/05/2026
    Como usar o comando return em funções Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python return Statement Explained Clearly

    Learn how Python return works, how it differs from print, how to return multiple values, avoid None bugs, and write

    Ler mais

    Tempo de leitura: 9 minutos
    21/05/2026
    Explicação prática de args e kwargs em funções Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python *args and **kwargs Explained Clearly

    Learn how Python *args and **kwargs work, when to use them, how unpacking works, and how to avoid common mistakes

    Ler mais

    Tempo de leitura: 8 minutos
    19/05/2026