Returns a number rounded to specified precision
round() returns a number rounded to ndigits precision after the decimal point.
If ndigits is not specified, the number is rounded to the nearest integer.
|number||Required||Specifies the number to round|
|ndigits||Optional||Specifies the number of decimal digits to round to.|
Default is None.
# Round a number 2.8 to the nearest integer x = round(2.8) print(x) # Prints 3
Rounding to decimal places
You can specify precision after the decimal point by using ndigits parameter.
# Round a number to only two decimals x = round(2.86542, 2) print(x) # Prints 2.87
Round To Ten’s or Hundred’s
ndigits can be negative as well. It allows you to e.g. round numbers to ten’s or hundred’s.
# Round to ten's x = round(48, -1) print(x) # Prints 50 x = round(148, -1) print(x) # Prints 150 # Round to hundred's x = round(248, -2) print(x) # Prints 200 x = round(268, -2) print(x) # Prints 300
If ndigits is not specified, the return value is an integer. Otherwise the return value has the same type as number.
# returns int x = round(2.865) print(x) # Prints 3 # returns float x = round(2.865, 0) print(x) # Prints 3.0
Rounding to Even (Banker’s Rounding)
In Python, if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then the even number is returned.
This kind of rounding is called rounding to even (or banker’s rounding).
x = round(4.5) print(x) # Prints 4 x = round(5.5) print(x) # Prints 6
If you want to explicitly round a number up or down, use ceil() or floor() function from math module.
# Round a number up import math x = math.ceil(4.5) print(x) # Prints 5 # Round a number down import math x = math.floor(4.5) print(x) # Prints 4