Learn Python – How to Round number in Python- Basic and advance

Python gives the built-in round() function, which used to spherical off a number to a given wide variety of digits. It takes the two arguments, first is n, second is n digits and then it returns range n after rounding it to ndigits. By default, it rounds off the wide variety n to the nearest integer.

For example – If we desire to round off a number, let’s suppose 7.5. It will be rounded off to the nearest complete wide variety is 7. However, the variety 7.56 will be rounded off to 7.5 via one places to give.

The round() function is critical when working with the quantity of floats that may additionally have many decimal places. The round() function makes handy and simple. The syntax is given below.

Syntax:

round(number, number of digits)  

The parameters are –

number – It represents the given number to be rounded.

number of digits(Optional) – It represents the number of digits up to which the given number is to be rounded.

Let’s understand the following example –

Example –

print(round(15))  
  
# For floating point  
print(round(25.8))  
print(round(25.4))  

Output:

15
26
25

Now, the second parameter is used.

Example –

print(round(25.4654, 2))  
  
# when the (ndigit+1)th digit is >=5  
print(round(25.4276, 3))  
  
# when the (ndigit+1)th digit is <5  
print(round(25.4173, 2))  

Output:

25.47
25.428
25.42

The real-life example of the round() function

The round() function is most beneficial whilst altering fractions to decimals. We commonly get the number of a decimal points such as if we do 1/3 then we get 0.333333334, however we use both two or three digits to the right of the decimal points. Let’s recognize the following example.

Example –

x = 1/6  
print(x)  
print(round(x, 2))  

Output:

0.16666666666666666
0.17

Another example

Example –

print(round(5.5))  
print(round(5))  
print(round(6.5))  

Output:

6
5
6

The round() feature rounds 5.5 up to 6 and 6.5 down to 6. This is not a bug, the round() behaves like this way.