Python round()
Function
The round() function in Python is used to round a number to the nearest integer or to a specified number of decimal places. It’s simple, effective, and very commonly used in mathematical and financial calculations.
Syntax
round(number, ndigits)
Parameters:
number
– The number to be rounded (int or float).ndigits
(optional) – The number of decimal places to round to. If omitted, it rounds to the nearest integer.
Returns:
- The rounded number (int if
ndigits
is not given; float ifndigits
is provided).
Example 1: Round to Nearest Integer
print(round(5.7))
6
Example 2: Round Down
print(round(5.4))
5
Example 3: Round to Decimal Places
print(round(3.14159, 2))
3.14
Use Case: Financial Rounding
amount = 123.4567
rounded_amount = round(amount, 2)
print("Final bill amount:", rounded_amount)
Final bill amount: 123.46
Rounding Even Numbers (Bankers’ Rounding)
Python uses “round half to even” also known as “bankers’ rounding.”
print(round(2.5)) # Rounds to even number
print(round(3.5)) # Also rounds to even number
2
4
Common Mistakes
- Passing a string instead of a number → raises
TypeError
- Expecting math.ceil or floor behavior – use
math.ceil()
ormath.floor()
for those cases - Assuming round always rounds up – it depends on the value and follows "round half to even"
Interview Tip
The round()
function is commonly used in data formatting and financial calculations. Be ready to explain how rounding works, especially the even-number rounding logic.
Summary
round(x)
→ rounds to nearest integerround(x, n)
→ rounds to n decimal places- Follows “round half to even” strategy (not always up)
Practice Problem
Ask the user to enter a number and the number of decimal places. Print the rounded result.
num = float(input("Enter a number: "))
decimals = int(input("Round to how many decimal places? "))
print("Rounded result:", round(num, decimals))