How to Use round() Function in Python: Syntax and Examples
Use the
round() function in Python to round a number to a specified number of decimal places. The syntax is round(number, digits), where digits is optional and defaults to 0, rounding to the nearest integer.Syntax
The round() function takes two arguments:
- number: The number you want to round.
- digits (optional): The number of decimal places to round to. If omitted, it rounds to the nearest integer.
python
round(number, ndigits=0)
Example
This example shows how to round numbers to different decimal places using round().
python
print(round(3.14159)) # Rounds to nearest integer print(round(3.14159, 2)) # Rounds to 2 decimal places print(round(3.14159, 3)) # Rounds to 3 decimal places print(round(123.456, -1)) # Rounds to nearest 10
Output
3
3.14
3.142
120.0
Common Pitfalls
Be careful with floating-point rounding errors because some decimal numbers can't be represented exactly in binary. Also, when rounding halfway values (like 2.5), Python rounds to the nearest even number (called bankers rounding).
Example of unexpected rounding:
python
print(round(2.5)) # Outputs 2, not 3 print(round(3.5)) # Outputs 4
Output
2
4
Quick Reference
| Usage | Description |
|---|---|
| round(number) | Rounds to nearest integer |
| round(number, digits) | Rounds to specified decimal places |
| round(number, negative_digits) | Rounds to left of decimal (e.g., -1 rounds to nearest 10) |
Key Takeaways
Use round(number, digits) to round numbers to a specific decimal place.
If digits is omitted, round() returns an integer.
Python uses bankers rounding for .5 values, rounding to the nearest even number.
Floating-point numbers may show small rounding errors due to binary representation.
Negative digits round to positions left of the decimal point.