Here are four ways to format float in Python:
- Using format()
- Using f-strings
- Using round() function
- Using the % operator
Method 1: Using format()
You can use the str.format() method to format floating-point numbers to a specific number of decimal places or in a specific format.
Visual Representation
Example 1: Formatting with two decimal places
value = 123.45678
formatted_value = "{:.2f}".format(value)
print(formatted_value)
print(type(formatted_value))
Output
123.46
<class 'str'>
The output returns a string. To convert the output to a float, use the float() function.
print(float(formatted_value))
print(type(float(formatted_value)))
Output
123.46
<class 'float'>
Example 2: Formatting with one decimal place
value = 123.45678
formatted_value = "{:.1f}".format(value)
print(float(formatted_value))
Output
123.5
Method 2: 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 like the % operator.
Visual Representation
Example
# Define a floating-point value
value = 123.45678
formatted_value = f"{value:.3f}"
print("Three decimals:",formatted_value)
formatted_value = f"{value:.2f}"
print("Two decimals:",formatted_value)
formatted_value = f"{value:.1f}"
print("One decimal:",formatted_value)
formatted_value = f"{value:.0f}"
print("No decimal:",formatted_value)
Output
Three decimals: 123.457
Two decimals: 123.46
One decimal: 123.5
No decimal: 123
Method 3: Using round() function
The round() function returns the floating-point number rounded off to the given digits after the decimal point.
It’s important to note that, if you want a string representation, you must convert it.
Visual Representation
Example
# Define a floating-point value
value = 123.45678
formatted_value = round(value, 3)
print("Three decimals:",formatted_value)
formatted_value = round(value, 2)
print("Two decimals:",formatted_value)
formatted_value = round(value, 1)
print("One decimal:",formatted_value)
Output
Three decimals: 123.457
Two decimals: 123.46
One decimal: 123.5
Method 4: Using the % Operator
The % operator is an older way of formatting strings and can be used for floats as well.
It works similar to format() method.
Visual Representation
Example
# Define a floating-point value
value = 123.45678
# Format the value to two decimal places
formatted_value = "%.2f" % value
print(formatted_value)
# Format the value to one decimal place
formatted_value = "%.1f" % value
print(formatted_value)
# Format the value to no decimal places
formatted_value = "%d" % value
print(formatted_value)
Output
123.46
123.5
123
Conclusion
The format() function is versatile and can handle various formatting needs, making it suitable for complex tasks.
If you are working with 3.6+ version, it’s recommended to use f-strings due to their conciseness and readability.
Justin
Thank you this was really helpful.