Practical Examples
Financial Calculations
def format_currency(amount):
return f"${amount:,.2f}"
total_sales = 1234567.89
print(f"Total Sales: {format_currency(total_sales)}")
Tax Calculation
def calculate_tax(price, tax_rate):
tax_amount = price * tax_rate
return f"Price: ${price:.2f}, Tax: ${tax_amount:.2f}"
product_price = 99.99
tax_rate = 0.08
print(calculate_tax(product_price, tax_rate))
Scientific Notation
Handling Large Numbers
def scientific_format(number):
return f"Scientific Notation: {number:.2e}"
galaxy_distance = 1_000_000_000_000
print(scientific_format(galaxy_distance))
Data Analysis Scenarios
def performance_report(accuracy):
return f"Model Accuracy: {accuracy:.2%}"
model_accuracy = 0.9345
print(performance_report(model_accuracy))
graph TD
A[Formatting Methods] --> B[% Operator]
A --> C[.format()]
A --> D[f-Strings]
B --> E[Legacy Approach]
C --> F[Modern Approach]
D --> G[Recommended Method]
Decimal Precision in Different Domains
Domain |
Precision |
Example |
Finance |
2 Decimals |
$123.45 |
Science |
4-6 Decimals |
0.123456 |
Engineering |
Variable |
1.23e-5 |
def advanced_report(value, precision=2):
return {
'raw': value,
'formatted': f"{value:.{precision}f}",
'percentage': f"{value:.{precision}%}",
'scientific': f"{value:.{precision}e}"
}
result = advanced_report(0.123456, 4)
for key, val in result.items():
print(f"{key.capitalize()}: {val}")
LabEx Pro Tip
At LabEx, we recommend practicing these formatting techniques across various scenarios to build robust numerical processing skills.
Key Takeaways
- Choose appropriate formatting based on context
- Understand precision requirements
- Use built-in Python formatting capabilities