Floating values can have many decimal places, making them difficult to read and interpret.
Formatting enables us to control the number of decimal places displayed and maintain consistency throughout our application.
Here are four ways to format floats in Python:
- Using f-strings (Python 3.6 or above)
- Using format()
- Using the % operator
- Using round()
Method 1: Using f-strings
Python 3.6 introduced f-strings (formatted string literals), which are a more readable and concise way to format strings compared to older methods, such as the % operator.
# Define a floating-point value
value = 123.45678
formatted_value = f"{value:.3f}"
print("Three decimals:", formatted_value)
# Output: Three decimals: 123.457
formatted_value = f"{value:.2f}"
print("Two decimals:", formatted_value)
# Output: Two decimals: 123.46
formatted_value = f"{value:.1f}"
print("One decimal:", formatted_value)
# Output: One decimal: 123.5
formatted_value = f"{value:.0f}"
print("No decimal:", formatted_value)
# Output: No decimal: 123
Method 2: Using format()
The str.format() method lets you format floating-point numbers to a specific number of decimal places or in a specific format.
Formatting with two decimal places
value = 123.45678
formatted_value = "{:.2f}".format(value)
print(formatted_value)
# Output: 123.46
print(type(formatted_value))
# Output: <class 'str'>
The output is a string. To convert the output to a float, use the float() function.
print(float(formatted_value)) # Output: 123.46 print(type(float(formatted_value))) # Output: <class 'float'>
Formatting with one decimal place
value = 123.45678
formatted_value = "{:.1f}".format(value)
print(float(formatted_value))
# Output: 123.5
Method 3: Using the % Operator
The % operator formats the strings oldway. You can use it for floats, and it works similarly to the format() method.
# Define a floating-point value value = 123.45678 # Format the value to two decimal places formatted_value = "%.2f" % value print(formatted_value) # Output: 123.46 # Format the value to one decimal place formatted_value = "%.1f" % value print(formatted_value) # Output: 123.5 # Format the value to no decimal places formatted_value = "%d" % value print(formatted_value) # Output: 123
Method 4: Using the round()
The round() function returns a floating-point number rounded to the specified number of digits after the decimal point. It does not return a string, and if you want, you must convert it.
# Define a floating-point value
value = 123.45678
formatted_value = round(value, 3)
print("Three decimals:", formatted_value)
# Output: 123.457
formatted_value = round(value, 2)
print("Two decimals:", formatted_value)
# Output: 123.46
formatted_value = round(value, 1)
print("One decimal:", formatted_value)
# Output: 123.5
That’s all!





Justin
Thank you this was really helpful.