In this Python tutorial, you will learn about the syntax and usage of Python round() function with example programs on how to use to round a floating point number.
Python round()
Python round() function rounds of a floating point number to specific number of decimal points.
Syntax
Following is the syntax of round() function.
round(number, precision)
where number is the floating point number with decimal part. precision specify the number of decimal digits the number has to round of.
round() function returns a rounded value of number with precision number of decimal places.
precision is optional. The default value of precision is zero. If no precision is specified, then round(number)
will become round(number, 0)
.
Examples
1. round() of a float number
In this example, we will initialize a variable pi
with a floating value and then round of its value to five decimal points.
Python Program
pi = 3.141592653589793238
pi_r = round(pi, 5)
print(pi_r)
Output
3.14159
In the following example, we compute rounded value of different floating point values.
Python Program
print(round(1.234, 2))
print(round(1.235, 2))
print(round(1.236, 2))
print(round(1.234999, 2))
Output
1.23
1.24
1.24
1.23
2. range() – With no Precision
If we do not give precision argument to round() function, the round() function will consider the default value of precision, which is zero.
In this example, we will initialize a variable pi
with a floating value and then round of its value to zero decimal points.
Python Program
pi = 3.141592653589793238
pi_r = round(pi)
print(pi_r)
Output
3
Python round() Tutorials
Following are some of the examples, that cover the special cases of round() function.
Conclusion
Concluding this Python Tutorial, we learned about Python round() function, its syntax, and the different scenarios associated with it.