Since Python 3.6, f-strings (formatted string literals) have become a powerful and elegant way to format strings. They allow you to insert dynamic expressions directly into strings, making the code more readable and concise.

In this tutorial, you will learn how to use f-strings to format and round floating-point numbers (floats), improving the display of your calculation results.

What is an F-String?

An f-string is a string literal prefixed with the letter f or F, containing replacement fields enclosed in curly braces {}. Within these fields, you can insert variables, functions, or calculations that will be evaluated at runtime. For example:

name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:

My name is John and I am 25 years old.

F-strings are flexible and allow you to customize number formatting, including rounding floats.

Formatting and Rounding Floats with F-Strings

One of the most useful features of f-strings is the ability to format floating-point numbers directly. This is done using format specifiers, which define precision, display type, and width.

Basic Example: Rounding Floats

Without explicit rounding, the result is displayed with high precision:

print(f"One-third as a float is: {1 / 3}")

Output:

One-third as a float is: 0.3333333333333333

To limit the decimal places, we use the .2f specifier:

print(f"One-third rounded to two decimal places is: {1 / 3:.2f}")

Output:

One-third rounded to two decimal places is: 0.33

Understanding the Format Specifier

  • :.2f:

    • 2: Defines the number of decimal places.

    • f: Indicates that the number is a float.

Practical Example with Variables and Functions

F-strings allow you to use variables and functions directly inside replacement fields. See this example:

def calculate_final_price(base_price):
    return base_price * 1.2

base_price = 1000
tax = 0.2

print(f"Base price: R${base_price:,.2f}, Tax: R${base_price * tax:,.2f}, Total: R${calculate_final_price(base_price):,.2f}")

Output:

Base price: R$1,000.00, Tax: R$200.00, Total: R$1,200.00

Explanation:

  • The thousand separator , was added before the decimal point . in the format specifier.

  • Functions can be called directly inside f-strings.

Working with Scientific Precision

To display numbers in scientific notation or with a fixed number of significant digits, use g or G:

import math
radius = 10.203
area = math.pi * radius**2

print(f"Area calculated with high precision: {area}")
print(f"Area rounded (5 significant digits): {area:.5g}")

Output:

Area calculated with high precision: 327.0435934242156
Area rounded (5 significant digits): 327.04

Displaying Numbers as Percentages

You can automatically display numbers as percentages using % in the format specifier:

percentage = 0.1256
print(f"Formatted percentage: {percentage:.1%}")

Output:

Formatted percentage: 12.6%

Customizing Field Width

You can define the total width of a field to align results. If the value does not fill the width, it will be padded with spaces.

value = 12345.6789
print(f"(1) |{value:.2f}|\n(2) |{value:10.2f}|\n(3) |{value:15.2f}|")

Output:

(1) |12345.68|
(2) |  12345.68|
(3) |      12345.68|

Tip:

To left-align, use the minus sign -:

print(f"|{value:<10.2f}|")  # Left-aligns the value

Output:

|12345.68  |

Conclusion

With f-strings, you have flexibility and simplicity to format floating-point numbers in Python, adapting the display for different contexts such as monetary values, percentages, or scientific precision. Use these techniques to improve the readability and presentation of your code.

Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source

Article link:http://pybeginners.com/article/how-to-format-and-round-floating-point-numbers-float-using-f-strings-in-python/