How to round off a number in Python?

PythonServer Side ProgrammingProgramming

Python has an inbuilt round() function to round off a number.

The round() method in Python takes two parameters −

  • The first one is the number to be rounded off.

  • The second one specifies the number of digits to which the number must be rounded off.

Here, the second parameter is optional.

If second parameter is not specified, then the round() method returns the integer using floor() and ceil().

It will look for the digits after the decimal.

  • If those are less than 5, it returns the floor() of the number passed.

  • Whereas if the digits after decimal are greater than 5, it returns the ceil() of the number passed.

  • If integer number is passed, then the same number is returned.

It will be more clear from the implementation below −

The round() function, when second parameter is absent.

The number to be rounded off is passed to the round() function. The output of round() in this case will always be an integer value.

Let us understand with an example.

Example

 Live Demo

print(round(15))
print(round(15.2))
print(round(15.8))
print(round(15.128))
print(round(15.89))

Output

15
15
16
15
16

Explanation

The explanation of all the print statements −

  • Integer 15 is passed, and the same integer is returned, hence output 15.

  • Number 15.2 is passed, the digits after decimal are less than 5, hence floor of 15.2 is returned, hence output 15.

  • Number 15.8 is passed, the digits after decimal are greater than 5, hence ceil of 15.8 is returned, hence output 16.

  • Number 15.128 is passed, the digits after decimal are less than 500, hence floor of 15.128 is returned, hence output 15.

  • Number 15.89 is passed, the digits after decimal are greater than 50, hence ceil of 15.89 is returned, hence output 16.

Note: All the outputs are integer values.

The round() function, when second parameter is present

The second parameter gives the number of digits to which the number must be rounded off.

Example

 Live Demo

print(round(15,2))
print(round(15.2789,3))
print(round(15.82,1))
print(round(15.128,2))
print(round(15.8902,2))

Output

15
15.279
15.8
15.13
15.89

The working of round() function, in this case, is the same as we calculate round off of a number mathematically.

In the case of integer value, the same integer value is returned, else the floating number rounded off to the specified number of digits is returned.

Explanation

  • The number is 15.2789 and the number of digits is 3. The 4th digit after decimal is greater than 5, hence the 3rd digit (the last specified digit) will be incremented by 1. Hence the output will be 15.279.

  • The number is 15.82 and the number of digits is 1. The 2 nd digit after decimal is less than 5, hence the 1st digit is not incremented by 1. Hence the output will be 15.8.

raja
Published on 10-Mar-2021 14:16:59
Advertisements