round () function in python

Python Methods and Functions

Syntax :

 round (number, number of digits) 

Parameters for round ():

 ..1) number - number to be rounded. 2) number of digits (Optional) - number of digits up to which the given number is to be rounded. 

If the second parameter is missing , the round () function returns :
..a) if only an integer equal to 15 is given, then it is rounded to 15.
..b) if decimal is given then it will round to whole CEIL after that if decimal is & gt; = 5, and it will round to an integer if gender decimal & lt; 5.

Below is the python implementation of the round () function if the second parameter is missing .

# for integers

print ( round ( 15 ))

 
# for floating point

print ( round ( 51.6 )) 

 

 

print ( round ( 51.5 )) 

 

print ( round ( 51.4 )) 

Exit :

 15 52 52 51 

When the second parameter is present, then it returns:
The last decimal digit to which it is rounded is incremented by 1 when the (ndigit + 1) th digit & gt; = 5, otherwise it remains the same.

Below is the Python implementation of the round () function if the second parameter is present.

# when (ndigit + 1) th digit = 5

print ( round ( 2.665 , 2 ))

 
# when (ndigit + 1) th digit & gt; = 5

print ( round ( 2.676 , 2 )) 

 
# when (ndigit + 1) th digit & lt; 5

print ( round ( 2.673 , 2 )) 

Exit :

 2.67 2.68 2.67 

Errors and Exceptions

Type error: This error occurs when the parameters contain something other than numbers.

print ( round ( "a" , 2 )) 

Exit:

  Runtime Errors:  Traceback (most recent call last): File "/home/ccdcfc451ab046030492e0e758d42461.py", line 1, in print (round ("a", 2)) TypeError: type str doesn 't define __round__ method 

Practical Application:
One of the common uses for rounding functions is to handle the mismatch between fractions and decimal numbers. 
One use of rounding numbers truncates all three to the right of the decimal point when converting 1/3 to decimal. In most cases, you will use the rounded numbers 0.33 or 0.333 when you need to work with 1/3 decimal. In fact, you usually work with two or three digits to the right of the decimal point when there is no exact decimal equivalent. How would you show 1/6 in decimal? Don't forget to round!

# practical use

b = 1 / 3

print (b)

print ( round (b, 2 )) 

Output :

 0.3333333333333333 0.33 

Note: if in Python we round numbers to the floor or up to the ceiling without specifying the second parameter, it returns 15,0, for example, and in Python 3 it returns 15, so to avoid this we can use (int) type conversion in Python.