Note
Python - round() - Round numbers to specified decimal places
Overview of the Python round() function: How to round numbers in Python
round(number, ndigits) is a built-in function used for rounding numbers in Python.
number: The number to round (can be a float or int).
ndigits (optional): Specifies the number of decimal places to round to. It can be:
-
positive integer: Round to the specified number of decimal places.
-
negative integer: Round to the left of the decimal point.
-
None(default): Round to the nearest integer.
Take a look at the examples below:
Basic Usage of round()
a = 2.586
rounded_a = round(a, 2)
print(rounded_a) # 2.59
Output:
2.59
REALLY Important Note: round() function rounds ties (.5 values) to the nearest even number. For example:
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(127.5)) # 128
Output:
2
4
128
Returned Type Matches the Input Type
Returned type corresponds with the provided argument, as shown below:
b = 3.0
rounded_b = round(b, 2)
print(rounded_b) # 3.0
print(type(rounded_b)) # <class 'float'>
c = 3
rounded_c = round(c, 2)
print(rounded_c) # 3
print(type(rounded_c)) # <class 'int'>
Output:
3.0
<class 'float'>
3
<class 'int'>
Using Negative ndigits
What is interesting in round() function, is that you can provide negative integers in place of the
ndigits argument. Take a look at that:
d = 329.262
rounded_d = round(d, 1)
print(rounded_d) # 329.3
rounded_d = round(d, 0)
print(rounded_d) # 329.0
rounded_d = round(d, -1)
print(rounded_d) # 330.0
rounded_d = round(d, -2)
print(rounded_d) # 300.0
rounded_d = round(d, -3)
print(rounded_d) # 0.0
Output:
329.3
329.0
330.0
300.0
0.0
As you can see providing negative integer as an ndigits argument results in rounding number "from the left side".
Rounding Without ndigits
Finally, if we don't provide an ndigits argument at all, we will always round the number to an integer type.
And naturally, Python won't have any problem with rounding negative numbers as well:
e = -3.14159
rounded_e = round(e)
print(rounded_e) # -3
print(type(rounded_e)) # <class 'int'>
Output:
-3
<class 'int'>
Key Points to Remember about the round() Function
-
Flexible Rounding: Works with both positive and negative values for
numberandndigits. -
Type Preservation: Returns a
floatorint, depending on the input type. -
Negative
ndigits: Rounds to positions to the left of the decimal point. -
Default Behavior: Without
ndigits, rounds to the nearestint.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!