Python Round Function
What does round() do?
The round()
function returns a number rounded to a given number of digits. By default, it rounds to the nearest integer.
Basic Syntax
round(number[, ndigits])
number
: The number to round.ndigits
: (Optional) The number of decimal places to round to. If omitted, rounds to the nearest integer.
Examples with integers and floats
print(round(3.14159)) # Output: 3
print(round(3.14159, 2)) # Output: 3.14
print(round(123.456, -1)) # Output: 120.0 (rounds to nearest 10)
Using the ndigits parameter
- If
ndigits
is positive, rounds to that many decimal places. - If
ndigits
is negative, rounds to the left of the decimal point.
Behavior with .5
- Python uses "banker's rounding" (rounds to the nearest even number when exactly halfway between two values).
print(round(2.5)) # Output: 2
print(round(3.5)) # Output: 4
Summary
round()
rounds a number to a specified number of digits.- Default is nearest integer.
- Uses banker's rounding for .5 cases.