Python tips: playing with round()

Python tips: playing with round()

You have probably already worked with the Python built-in round() function. It takes a number as an argument and simply rounds it. But depending on its second parameter, the function can actually perform a range of rounding calculations with different types of precision. As you'll see later, you can even pass negative numbers as parameters.

To begin with, round() can simply take one value as a required argument to perform a standard rounding operation:

>>> round(1.2489)  # <- returns the nearest integer
1
>>> round(1.5)
2
>>> round(2.5)
2

If rounding both 1.5 and 2.5 to 2 is not precise enough for you, round() accepts the second parameter to represent the number of digits from the decimal point you wish your number to be rounded to. Just like that:

>>> num = 1.28372
>>> round(num, 1)
1.3
>>> round(num, 2)
1.28
>>> round(num, 3)
1.284

We can now round the numbers from the chunk of code above more precisely:

>>> round(1.2489, 2)
1.25
>>> round(1.5, 2)
1.5
>>> round(2.5, 2)
2.5

The more interesting thing is that round() also accepts negative numbers as the second argument and, in this case, rounding takes place for tens, hundreds, thousands, and so on:

>>> num = 274895
>>> round(num, -1)
274900
>>> round(num, -2)
274900
>>> round(num, -5)
300000

And a bit more surprisingly:

>>> round(num, -6)
0

If you pass in a floating point value with a negative parameter, the function will return a float instead of an integer:

>>> num = 274895.56
>>> round(num, -1)
274900.0
>>> round(num, -2)
274900.0

Hope you enjoyed my post! If you did, don't forget to like it. Thank you :)