Python round() Function Explained with Practical Examples
Python round() Function Explained
The round() built‑in is a staple for numerical work in Python. It returns a value rounded to a specified number of decimal places, defaulting to the nearest integer when no precision is provided.
Syntax
round(number, ndigits=None)
- number – The numeric value to round.
- ndigits – Optional; the number of decimal places to keep. If omitted, the result is an integer.
Return Value
When ndigits is omitted, round() returns an int. If ndigits is supplied, the result is a float rounded to that precision.
Rounding Rules
- If the digit following the target place is 5 or greater, the value is rounded up.
- If it is less than 5, the value is truncated at the specified precision.
Why Rounding Matters: A Real‑World Example
In financial markets, rounding can influence millions of dollars in trading. For instance, the Vancouver Stock Exchange in 1982 truncated trade prices to three decimal places, leading to a cumulative monthly loss of about 25 points. Rounding instead of truncating yields far tighter results.
# Example: Truncating vs. Rounding
import random
def truncate(num):
return int(num * 1000) / 1000
arr = [random.uniform(0.01, 0.05) for _ in range(1_000_000)]
# Truncation
sum_truncate = 0
for val in arr:
sum_truncate = truncate(sum_truncate + val)
# Rounding
sum_round = 0
for val in arr:
sum_round = round(sum_round + val, 3)
print("Truncated sum:", sum_truncate)
print("Rounded sum:", sum_round)
The truncated total can deviate by hundreds of units, whereas rounding keeps the deviation to a fraction of a unit.
Common Use Cases
Rounding Floating‑Point Numbers
# Basic rounding print(round(10.60)) # 11 print(round(10.40)) # 10 print(round(10.3456, 2)) # 10.35 print(round(10.3445, 2)) # 10.34
Rounding Integers
print(round(15)) # 15
Rounding Negative Numbers
print(round(-2.8)) # -3 print(round(-1.5)) # -2
Rounding Numpy Arrays
import numpy as np arr = [-0.341111, 1.455098989, 4.232323, -0.3432326, 7.626632, 5.122323] print(np.round(arr, 2)) # [-0.34 1.46 4.23 -0.34 7.63 5.12]
Using the Decimal Module for Precision
The decimal module offers finer control over rounding modes.
import decimal
num = decimal.Decimal('15.456')
print(num.quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)) # 15.46
Key Takeaways
- Use
round(number, ndigits)for standard rounding. - Omitting
ndigitsreturns an integer; providing it returns a float. - For critical financial or scientific calculations, consider
decimalfor deterministic rounding.
Python
- Python Print() Function: A Practical Guide with Examples
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
- Master Python’s str.count(): How to Count Characters & Substrings with Examples
- Master Python `format()` Strings with Clear Examples
- Master Python's String.find() Method: Syntax, Examples & Alternatives
- Master Python Lambda Functions: Practical Examples & Best Practices
- Mastering Python's map() Function: Syntax, Examples, and Best Practices
- Python timeit() – Measuring Execution Time with Practical Examples
- Python list.count(): Expert Guide with Practical Examples
- Python Module Importing – A Practical Guide with Examples