Practical Rounding Examples
Financial Calculations
Currency Rounding
from decimal import Decimal, ROUND_HALF_UP
def round_currency(amount):
"""Round currency to two decimal places"""
return Decimal(amount).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
## Example transactions
prices = [10.456, 25.674, 33.215]
rounded_prices = [round_currency(price) for price in prices]
print(rounded_prices) ## Outputs [10.46, 25.67, 33.22]
Tax Calculation Example
def calculate_total_with_tax(price, tax_rate):
"""Calculate total price with rounded tax"""
tax = round(price * tax_rate, 2)
total = round(price + tax, 2)
return total
## Tax calculation
item_price = 100.00
tax_rate = 0.08
total_price = calculate_total_with_tax(item_price, tax_rate)
print(f"Total Price: ${total_price}")
Scientific and Data Analysis
Measurement Rounding
import numpy as np
def round_measurements(measurements, precision=2):
"""Round scientific measurements"""
return np.round(measurements, decimals=precision)
## Temperature measurements
temperatures = [23.456, 24.789, 22.345]
rounded_temps = round_measurements(temperatures)
print(rounded_temps) ## Outputs [23.46, 24.79, 22.35]
graph TD
A[Rounding in Performance] --> B[Metrics Calculation]
A --> C[Statistical Analysis]
A --> D[Machine Learning]
def calculate_performance_score(raw_score):
"""Round performance scores"""
if raw_score < 0:
return 0
elif raw_score > 100:
return 100
else:
return round(raw_score, 1)
## Performance score examples
scores = [-5, 85.6789, 102.5]
normalized_scores = [calculate_performance_score(score) for score in scores]
print(normalized_scores) ## Outputs [0, 85.7, 100]
Comparison of Rounding Techniques
Scenario |
Recommended Method |
Precision |
Financial |
Decimal Module |
Exact |
Scientific |
NumPy Rounding |
Configurable |
General |
Built-in round() |
Simple |
Machine Learning Preprocessing
def normalize_features(features, decimal_places=3):
"""Normalize and round machine learning features"""
return [round(feature, decimal_places) for feature in features]
## Feature normalization
raw_features = [0.123456, 0.987654, 0.456789]
normalized_features = normalize_features(raw_features)
print(normalized_features) ## Outputs [0.123, 0.988, 0.457]
Best Practices
- Choose rounding method based on context
- Consider precision requirements
- Be consistent in rounding approach
- Handle edge cases explicitly
LabEx recommends understanding these practical examples to master float rounding in Python across various domains.