Rounding in Python

Python has a built-in round() function that takes two numeric arguments, number and ndigits, and returns a floating point number that is a rounded version of the number up to the specified number of decimals.

The default number of decimal is 0, meaning that the function will return the nearest integer.

The round() function in Python will round to the nearest whole number and ‘rounding to the even number’ when equidistant, meaning that exactly 12.5 rounds to the integer 12.

# For integers
x= 12
print(round(x))
 
# For floating point
x= 12.3
print(round(22.7))  
 
# if the second parameter is present
 
# when the (ndigit+1)th digit is =5 
x=4.465
print(round(x, 2)) 
   
# when the (ndigit+1)th digit is >=5 
x=4.476
print(round(x, 2))   
   
# when the (ndigit+1)th digit is <5 
x=4.473
print(round(x, 2))
12
23
4.46
4.48
4.47