Python round() function
The round()
function in Python is used to round a floating-point number to a specified number of decimal places, or to the nearest integer if no decimal places are specified.
Syntax
number
: The number you want to round.ndigits
(optional): The number of decimal places to round to. If omitted, it defaults to0
, meaning the number will be rounded to the nearest integer.
Return Value
- If
ndigits
is provided, it returns the number rounded to the specified decimal places. - If
ndigits
is omitted or0
, it returns the nearest integer. - For negative numbers, it rounds towards zero (also known as rounding half to even).
Examples
Rounding to the nearest integer (default behavior):
Rounding to specific decimal places: You can specify the number of decimal places using the
ndigits
argument:Rounding with
ndigits = 0
(explicit integer rounding):Rounding negative numbers:
Rounding to negative decimal places: You can also round numbers to negative decimal places, which rounds to the nearest tens, hundreds, etc.
How It Handles Halfway Cases (Banker's Rounding)
The round()
function uses a technique called rounding half to even, also known as banker's rounding. This means that when a number is exactly halfway between two integers (like 2.5
or 3.5
), it rounds towards the nearest even number.
Example:
Summary
round()
is used to round numbers to a specified number of decimal places.- It uses rounding half to even for numbers that are exactly halfway between two values.
- Can handle rounding both positive and negative numbers.