Home >Backend Development >Python Tutorial >How to Display Floats with Two Decimal Places in Python?
Displaying Floats with Two Decimal Places in Python
When working with floating-point numbers, it often becomes necessary to display them with a specific number of decimal places. In Python, there are several ways to achieve this using string formatting.
Using the %.2f Format Specifier
The traditional method of formatting floats with two decimal places is to use the % operator and the f format specifier:
number = 5.5 formatted_number = "%.2f" % number print(formatted_number) # Output: 5.50
This method works by replacing the % placeholder in the format string with the formatted number. The .2 part indicates that the float should have two decimal places.
Using f-Strings
In Python 3.6 and later, f-strings provide a more concise syntax for formatting strings:
number = 5.5 formatted_number = f"{number:.2f}" print(formatted_number) # Output: 5.50
F-strings follow a similar concept as the % operator, but the format specifier is placed within curly braces inside the string.
Using Decimal.quantize()
For more precise control over the formatting, the Decimal module offers a quantize() method:
from decimal import Decimal number = Decimal("5.5") formatted_number = number.quantize(Decimal(".01")) print(formatted_number) # Output: 5.50
quantize() takes a Decimal object representing the desired rounding precision. In this case, we round to the nearest hundredth (two decimal places).
The above is the detailed content of How to Display Floats with Two Decimal Places in Python?. For more information, please follow other related articles on the PHP Chinese website!