round()
round() rounds a number to the nearest integer, or to as many decimals as you ask for.
Used in 34 lessons of the course, from 00.05.
round(x) returns the integer closest to x. round(x, n) returns a number with n decimals and keeps the type: a float stays a float.
When the value sits exactly halfway, Python rounds to the nearest even integer. So round(2.5) gives 2 and round(3.5) gives 4. It works this way so errors don't always pile up in the same direction.
Floats also store a binary approximation, so round(2.675, 2) gives 2.67, not 2.68.
The course uses it in round(seconds, 2): it takes the time the model needed and keeps two decimals so the response dict is readable. Note that round changes the value. If you only want to display two decimals, an f-string with :.2f does it without altering the number.
Reach for it when: you want to store or return a number with fewer decimals, like a measured time or an average.
Examples
Common mistake
print(round(2.5))
Why: Many expect 3, as taught in school. Python rounds halves to the even integer.
How to write it: If you need halves to always go up, use decimal with ROUND_HALF_UP.
Common mistake
print(round(2.675, 2))
Why: The float 2.675 is stored as a value slightly below 2.675, so it rounds down.
How to write it: For money or exact decimals, use decimal.Decimal.
