This article explains the Python round() function in detail with examples.
Syntax of round() function
The syntax of the round() function is as follows:
round(floating-point number, digits)
The round() function two parameters as arguments, i.e., floating-point number and digits. The number or floating-point number is the required parameter, whereas the number of digits is the optional parameter. In case if we do not provide the number of digits, then the round() function will return the closest integer number. We can also provide the integer number in the first parameter. In this case, the round() function will return the same integer number.
Examples and usage of round() function
Let’s see the examples and usage of the round() function in our Python script. If we do not specify the number of digits, then the round() function takes the ceil of the number and convert it into the next integer if the decimal value is greater than 5. In case if the decimal value is less than equal to the 5, then it takes the floor value, and the integer number remains the same.
#not specifying the number of digits
print(round(10.1))
print(round(10.5))
print(round(10.7))
print(round(11.9))
print(round(15.3))
print(round(17.8))
print(round(20))
print(round(20.01))
Output
Now, let’s define the number of digits and use the round() function.
print(round(10.123,2))
print(round(10.587,1))
print(round(10.72,1))
print(round(11.9545,1))
print(round(15.322,2))
print(round(17.865,2))
print(round(20.090,2))
print(round(20.01114,2))
Output
Now, let’s take some integer values and apply the round() function. You can note that in the output, then unchanged integer value is returned.
print(round(10))
print(round(20))
print(round(30))
print(round(40))
print(round(50))
print(round(12))
print(round(15))
print(round(19))
Output
If we pass any string or character to the round() function instead of a number, the Python interpreter will throw an error.
print(round('kamran'))
Output
Rounding off the negative numbers
The round() function can be applied to negative numbers as well, and it rounds off the negative numbers and returns the result.
num = -3.98
print(round(num,1))
num = -2.8
print(round(num))
num = -5.67989
print(round(num,2))
num = -100.9843
print(round(num,1))
num = -20.04
print(round(num))
num = -32.0908
print(round(num,3))
num = -3.9898
print(round(num))
Output
Conclusion
The round() is a built-in function of Python that rounded off the floating-point number to the given decimal numbers. It is a very useful function when you are performing the numbers related task. This article briefly explains the round() function with examples.
from Linux Hint https://ift.tt/2Tqr3Xl
0 Comments