How to Format Float to 2 Decimal Places in Python
To format a float to 2 decimal places in Python, use
f"{value:.2f}" for f-strings or format(value, ".2f"). These methods convert the float to a string with exactly two digits after the decimal point.Syntax
Here are common ways to format a float to 2 decimal places in Python:
f"{value:.2f}": Uses f-string formatting to show 2 decimals.format(value, ".2f"): Uses theformat()function to format the float.round(value, 2): Rounds the float to 2 decimals but returns a float, not a formatted string.
python
value = 3.14159 formatted_fstring = f"{value:.2f}" formatted_format = format(value, ".2f") rounded_value = round(value, 2) print(formatted_fstring) print(formatted_format) print(rounded_value)
Output
3.14
3.14
3.14
Example
This example shows how to format a float number to 2 decimal places using f-strings and format(). It prints the formatted strings and the rounded float.
python
price = 12.98765 # Using f-string formatted_price_fstring = f"{price:.2f}" # Using format() function formatted_price_format = format(price, ".2f") # Using round() function rounded_price = round(price, 2) print("Formatted with f-string:", formatted_price_fstring) print("Formatted with format():", formatted_price_format) print("Rounded value:", rounded_price)
Output
Formatted with f-string: 12.99
Formatted with format(): 12.99
Rounded value: 12.99
Common Pitfalls
One common mistake is expecting round() to format the number as a string with trailing zeros. It returns a float, which may not display trailing zeros. Also, using string formatting incorrectly can cause errors or unexpected output.
Wrong way:
value = 2.5
print(f"{value:2f}") # Missing dot before 2Right way:
value = 2.5
print(f"{value:.2f}") # Correct syntaxpython
value = 2.5 # Wrong formatting - missing dot try: print(f"{value:2f}") except Exception as e: print("Error:", e) # Correct formatting print(f"{value:.2f}")
Output
Error: Invalid format specifier
2.50
Quick Reference
| Method | Description | Returns |
|---|---|---|
| f-string | Formats float to 2 decimals as string | String |
| format() | Formats float to 2 decimals as string | String |
| round() | Rounds float to 2 decimals, returns float | Float |
Key Takeaways
Use f-strings with
:.2f to format floats to 2 decimal places as strings.The
format() function also formats floats to 2 decimals and returns a string.The
round() function rounds floats but returns a float, which may not show trailing zeros.Always include the dot before the number in format specifiers, like
:.2f, to avoid errors.Formatted floats are strings; use rounding if you need a numeric float value.