The built-in function round() is used to return the floating-point number which is a rounded version of a given decimal number with a specified number of digits.
round(number, ndigits) #where number can be int,float.
Takes two parameters. The function will return the nearest integer, if the default number of decimals is 0.
Parameter | Description | Required / Optional |
---|---|---|
number | the number to be rounded | Required |
ndigits | number up to which the given number is rounded; defaults to 0 | optional |
Any integer value is valid for ndigits that is its value may be positive, zero, or negative. If the value after the decimal point is >=5 then the value will be rounded to +1 else it returns the value as it is up to the decimal places mentioned.
Input | Return Value |
---|---|
If ndigits is not given. | returns the nearest integer to the given number. |
If ndigits | returns the number rounded off to the ndigits |
# for integers
print(round(10))
# for floating point
print(round(10.7))
# even choice
print(round(5.5))
Output:
10 11 6
print(round(2.665, 2))
print(round(2.675, 2))
Output:
2.67 2.67
class Data:
id = 0
def __init__(self, i):
self.id = i
def __round__(self, n):
return round(self.id, n)
d = Data(10.5234)
print(round(d, 2))
print(round(d, 1))
Output:
10.52 10.5