round() function in Python

In this tutorial, we will learn to use the round() function in Python. We use this function to round off any floating number to a given number of digits after the decimal point. If no such number is provided, then it returns the nearest integer.

Syntax of round()

The syntax for the round() function is as follows:

round(number, digits)

In the above syntax, the first parameter is the number that we are trying to round off and the second parameter is the number of digits after the decimal point up to which the given number will be rounded off.

Working  of round() function in Python

If the given number is an integer, then the function returns the same number. If the number is a float, then it rounds off the number based on the following rules:

  • If the digit after the digit up to which we have to round off the number is greater than or equal to 5 then the preceding digit is incremented by 1 and all the digits following that digit are eliminated. i.e 14.89875 is rounded as 14.899 up to 3 digits after the decimal point.
  • If the digit after the digit up to which we have to round off the number is less than 5 then the preceding digits are retained as they are and the rest of the digits are eliminated. i.e. 14.89433 is rounded as 14.894 up to 3 digits after the decimal point.
  • If the second parameter is absent then the number is rounded up to the nearest integer.

Example Program

An example program that illustrates the working of the round() function has been given here.

print(round(14))
print(round(14, 2))
print(round(14.89875, 3))
print(round(14.89433, 3))
print(round(14.89))
print(round(14.33))

The output of the given example program is:

14
14
14.899
14.894
15
14

Thank you.

Also, read: Python divmod() function

Leave a Reply

Your email address will not be published. Required fields are marked *