Python round

Table of Contents

Introduction

This article aims to explain how you can round a number using Python.
Proceed to the next sections to learn everything you need to know about the round() function and see many examples.

Python round function

The built-in Python round() function allows you to round a number.
This function is simple to use as its syntax is very intuitive:

rounded_number = round(number[, ndigits])

More in details, this function returns the number rounded to ndigits precision after the decimal point.
If ndigits is omitted or is None, it returns the nearest integer to its input.

From the definition above, you will surely understand that the ndigits parameter is optional.
In fact, if it is not passed, it is as if the default value was 0.

Python round – without number of decimals

This chapter shows you how you can use the round() function without specifying the number of decimal places.

print(round(3.65))
print(round(0.12))
print(round(1.555558))
print(round(23.05))
print(round(3))

Output

4
0
2
23
3

As you can see from the examples, this function rounds the number to the nearest integer, completely excluding the decimal part.
I would like to point out that if the number is not a decimal, no operation is applied.
In the next chapter, however, we will see how it is possible to use the same function by specifying the number of decimal places to keep.

Python round – with number of decimals

This chapter shows you how you can use the round() function specifying the number of decimal places.

print(round(3.65, 2))
print(round(0.12, 3))
print(round(1.555558, 2))
print(round(23.05, 1))
print(round(3, 4))

Output

3.65
0.12
1.56
23.1
3

As you can see, by specifying the second parameter it is possible to round the numbers to a certain decimal place.
More in details, the function will return a rounded number keeping the specified number of decimal places.
This is very useful when you need to round numbers to some precision.

Conclusion

Here we are at the end of this post, as always I hope this article will be useful to you and that now you know how to make the most of the Python round function.
If you find that something is unclear or you have a problem that you don’t know how to solve, leave me a comment below and I will try to help you as soon as possible.

If this topic is clear to you, take a look at the latest posts!

Leave a Comment

Your email address will not be published. Required fields are marked *