Home > Backend Development > Python Tutorial > How to Display Floats with Two Decimal Places in Python?

How to Display Floats with Two Decimal Places in Python?

Barbara Streisand
Release: 2024-12-02 11:12:11
Original
181 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template