The round() function in Python is used to round a floating-point number to a specified number of digits. It’s a built-in function that makes rounding numbers straightforward.
Basic Syntax
round(number, ndigits=None)
Where:
- number: The number you want to round.
- ndigits (optional): The number of decimal places to round to.
Examples
Rounding to the nearest integer:
print(round(3.14159)) # Output: 3
Rounding to two decimal places:
print(round(3.14159, 2)) # Output: 3.14
Rounding Negative Numbers
The round()
function works with negative numbers as well:
print(round(-2.71828)) # Output: -3
Banker’s Rounding
Python’s rounding follows the banker’s rounding method, which rounds to the nearest even number when the number is exactly halfway between two integers:
print(round(2.5)) # Output: 2
print(round(3.5)) # Output: 4
Conclusion
The round()
function is a handy tool for rounding numbers in Python. Understanding its behavior ensures accurate numerical computations in your programs.