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.
Using round()
round() function is the most efficient way to round a number to a specified number of decimal places. It directly returns the rounded value without any additional overhead.
Example:
n= 3.14159
# rounding `n` to 2 decimal places
res = round(n, 2)
print(res)
Output
3.14
Let's explore other methods of rounding floating value to two decimals in python:
Table of Content
Using decimal module
In Python, we can use the decimal module to round floating-point numbers to a specific number of decimal places with higher precision and control compared to the built-in floating-point arithmetic.
from decimal import Decimal, getcontext, ROUND_HALF_UP
# Step 1: Create a Decimal object from a floating-point number
n1 = Decimal('123.4567')
# Step 2: Define the rounding context
# '0.01' specifies that we want to round to two decimal places
n2 = n1.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(n2)
Output
123.46
Using % 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.
n1 = 3.14159
# Formatting the number to display two decimal places
n2 = "%.2f" % n1
print(n2)
Output
3.14
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.
n1 = 3.14159
n2 = f"{n1:.2f}"
print(n2)
Output
3.14