The Python round function is one of the Built-in Math function which is used to round the specified expression or an individual number to nearest integer.
In this article we will show you, How to use round function in Python Programming language with example.
The basic syntax of the round Function in Python Programming is as shown below:
round(Number, Digits);
Number: It can be a number or a valid numerical expression.
- If the number argument is positive or negative number, round() function will return the nearest value.
- If the number argument is not a number, round() function will return TypeError
Digits: This is optional parameter. If you omit this argument, round() Function will round the Number to nearest integer value otherwise, Number is rounded to decimal value specified in Digits arguments.
Python round Function Example
The Python round function is used to round the number to nearest integer. In this example, We are going to round the values of different data types and display the output
# Python round Function Tup = (10.98, 20.26, 30.05, -40.95 , 50.85) # Tuple Declaration Lis = [-10.98, 32.65, -39.29, -42.15 , -39.97] # List Declaration print('round() Function on Positive Decimal = %.2f' %round(10.98763)) print('round() Function on Negative Decimal = %.2f' %round(-15.48476)) print('round() Function with Second argument = %.3f' %round(10.98763, 3)) print('round() Function with Second argument = %.3f' %round(-15.48476, 3)) print('round() Function on Tuple Item = %d' %round(Tup[2])) print('round() Function on Tuple Item = %d' %round(Tup[4])) print('round() Function on List Item = %d' %round(Lis[2])) print('round() Function on List Item = %d' %round(Lis[4])) print('round() Function on Multiple Number = %.2f' %round(10 + 20 - 40.6578, 2)) print('round() Function on String Value = ', round('2.95'))
OUTPUT
ANALYSIS
- At the beginning of this program, We declared a Python List and Tuple with some random values.
- The First two statements of this program, We used the Python round Function directly on both the Positive decimals and negative decimals.
- Next two statements, We used the round() Function with two arguments so above statements will round the given numbers to nearest decimal value at third position.
- Next four statements, We used the round() Function on Tuple and List items. If you observe the above screenshot, round() function is working perfectly on them.
- Then, We tried Python round() Function directly on multiple values
- Last, We tried round() Function on String value. As we said before, this will return TypeError as an output
Thank You for Visiting Our Blog