How to Round Floating Value to Two Decimals in Python
In this article, we will round off a float value in Python to the nearest two decimal places. Python provides us with multiple approaches to format numbers to 2 decimal places.
Get Two Decimal Places in Python
Below are some of the approaches by which we can get two decimal places in Python:
- Using round() Function
- String Formatting with
%
Operator - Using f-strings
Round Floating Value to Two Decimals Using the round() Function
In this example, a floating-point number, 3.14159, is rounded to two decimal places using the round() Function.
number = 3.14159
# rounding the above number
rounded_number = round(number, 2)
print(rounded_number)
Output
3.14
Round Floating Value to Two Decimals with % Operator
String formatting with the %
operator allows us to control the presentation of a string or number. We can use string formatting with % operator to format a float value to two decimal places. Here we are using string formatting with % operator to round the given value up to two decimals.
number = 3.14159
# Formatting the number to display two decimal places
formatted_number = "%.2f" % number
print(formatted_number)
Output
3.14
Round Floating Value to Two Decimals Using f-strings
f-strings can be used to round off a float value to two decimal places. Here, we are using f-strings to round the given value up to two decimals.
number = 3.14159
formatted_number = f"{number:.2f}"
print(formatted_number)
Output
3.14
Contact Us