Skip to content

Python float decimal places

  • by

To specify the number of decimal places when working with floats in Python, you can use string formatting or the round() function. Here’s the syntax for each approach:

String formatting:

formatted_num = "{:.nf}".format(num)

f-strings (Python 3.6+):

formatted_num = f"{num:.nf}"

round() function:

rounded_num = round(num, n)
  • Replace n with the desired number of decimal places.
  • num is the floating-point number you want to format.

These methods allow you to control the number of decimal places when working with floats in Python.

Python float decimal places example

Here are a few examples of working with floats and specifying the number of decimal places in Python:

Example 1: Using string formatting

num = 3.14159
formatted_num = "{:.2f}".format(num)
print(formatted_num)  # Output: 3.14

Example 2: Using f-strings

num = 3.14159
formatted_num = f"{num:.2f}"
print(formatted_num)  # Output: 3.14

Example 3: Using the round() function

num = 3.14159
rounded_num = round(num, 2)
print(rounded_num)  # Output: 3.14

Example 4: Truncating extra decimal places

num = 3.1499999
formatted_num = "{:.2f}".format(num)
print(formatted_num)  # Output: 3.15

Example 5: Displaying trailing zeros

num = 3.1
formatted_num = "{:.2f}".format(num)
print(formatted_num)  # Output: 3.10

Let’s say you have a program that calculates the average temperature over a certain period of time. The temperature values are represented as floats, and you want to display the average temperature with two decimal places.

temperatures = [23.5, 24.1, 22.8, 25.3, 23.9]

# Calculate the average temperature
average_temp = sum(temperatures) / len(temperatures)

# Display the average temperature with two decimal places
formatted_avg_temp = "{:.2f}".format(average_temp)
print("The average temperature is:", formatted_avg_temp)

Output:

Python float decimal places

By controlling the number of decimal places, we ensure that the average temperature is displayed with the desired level of precision.

Do comment if you have any doubts or suggestions on this Python float topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading