Back to Blog Home

How to round a number in Python

Jay Mishra| Python | 6 months, 2 weeks



 

Rounding off a number to given number of digits is pretty straightforward in python as it provides an unbuilt function round() which takes in two arguments : the number to be rounded and number of digits to round it off to. The second argument is optional and when it is not provided, it automatically consider its default value of 0.  It returns a float. 

 

So the syntax of rounding off a number in python looks like :

 

Syntax:

round(number, number of digits)

 

number - number to be rounded off

number of digits - number of digits to round off the number to

 

 

When number of digits is not mentioned :

 

>>print(round(9))

>>9

round() method rounds off an integer

 

>>print(round(21.6)) 

>>22

round() rounds off to ceil integer when decimal is > 5 

 

>>print(round(21.5))

>>22  

round() rounds off to ceil integer when decimal is = 5

 

>>print(round(21.4)) 

>>21

round() rounds off to floor integer when decimal is < 5

 

 

When number of digits is mentioned :

 

 

# when the (ndigit+1)th digit is =5

>>print(round(1.225, 2))

>>1.23

 

# when the (ndigit+1)th digit is >=5

>>print(round(1.226, 2))

>> 1.23

 

# when the (ndigit+1)th digit is <5 

>>print(round(1.223, 2))

>>1.22 

 



Join 1000+ People Who Subscribe to Weekly Blog Updates

Back to Blog Home