Advanced Rounding Tips
Handling Floating-Point Precision
Avoiding Floating-Point Errors
## Common precision pitfall
print(0.1 + 0.2 == 0.3) ## False
## Recommended approach
import math
def float_equal(a, b, tolerance=1e-9):
return math.isclose(a, b, rel_tol=tolerance)
print(float_equal(0.1 + 0.2, 0.3)) ## True
Rounding Strategies Flowchart
graph TD
A[Rounding Decision] --> B{Precision Requirement}
B --> |High| C[Decimal Module]
B --> |Medium| D[round() Function]
B --> |Low| E[Math Module Methods]
Decimal Module for Precise Calculations
from decimal import Decimal, getcontext
## Set precision
getcontext().prec = 6
## Precise financial calculations
price = Decimal('10.235')
tax_rate = Decimal('0.07')
total = price * (1 + tax_rate)
print(total.quantize(Decimal('0.01'))) ## 10.95
| Rounding Method |
Precision |
Performance |
| round() |
Medium |
Fast |
| Decimal Module |
High |
Slower |
| NumPy |
High |
Fastest for arrays |
Custom Rounding Functions
def custom_round(number, base=0.05):
"""
Round to nearest specified base
Useful for pricing strategies
"""
return base * round(number / base)
## Example usage
print(custom_round(1.23)) ## 1.25
print(custom_round(2.37)) ## 2.35
Handling Different Number Types
def smart_round(value, decimals=2):
"""
Intelligent rounding for various number types
"""
try:
return round(float(value), decimals)
except (TypeError, ValueError):
return value
## Various input types
print(smart_round(3.14159)) ## 3.14
print(smart_round('3.14159')) ## 3.14
print(smart_round(42)) ## 42.0
NumPy Rounding Techniques
import numpy as np
## Array rounding
numbers = np.array([1.234, 2.345, 3.456])
print(np.round(numbers, 2)) ## [1.23 2.35 3.46]
LabEx Recommendation
When working in LabEx Python environments, choose rounding methods based on:
- Required precision
- Performance needs
- Specific use case
Error Handling in Rounding
def safe_round(value, decimals=2):
"""
Robust rounding with error handling
"""
try:
return round(float(value), decimals)
except (TypeError, ValueError):
print(f"Cannot round {value}")
return None
## Safe rounding
print(safe_round(3.14159)) ## 3.14
print(safe_round('invalid')) ## None