Practical Examples
1. Financial Calculations
def calculate_tax(amount, rate):
tax = amount * rate
return f"Total Tax: ${tax:.2f}"
income = 5000.75
tax_rate = 0.15
print(calculate_tax(income, tax_rate)) ## Displays: Total Tax: $750.11
2. Scientific Data Processing
def format_scientific_data(measurements):
return [f"{m:.3e}" for m in measurements]
sensor_readings = [0.00456, 123.456, 0.000789]
formatted_readings = format_scientific_data(sensor_readings)
print(formatted_readings)
graph TD
A[Raw Data] --> B[Float Formatting]
B --> C[Cleaned Data]
C --> D[Visualization]
def performance_report(response_times):
avg_time = sum(response_times) / len(response_times)
return {
'average': f"{avg_time:.3f} ms",
'min': f"{min(response_times):.3f} ms",
'max': f"{max(response_times):.3f} ms"
}
times = [0.234, 0.567, 0.123, 0.456]
report = performance_report(times)
print(report)
Scenario |
Format Specifier |
Purpose |
Currency |
.2f |
Two decimal places |
Scientific |
.3e |
Exponential notation |
Percentage |
.1% |
Percentage display |
4. Temperature Conversion
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return f"{celsius}ยฐC = {fahrenheit:.1f}ยฐF"
temperatures = [0, 25, 100]
for temp in temperatures:
print(celsius_to_fahrenheit(temp))
5. Precision Control in Machine Learning
def model_accuracy(predictions, actual):
accuracy = sum(p == a for p, a in zip(predictions, actual)) / len(actual)
return f"Model Accuracy: {accuracy:.4%}"
predictions = [1, 0, 1, 1, 0]
actual_values = [1, 0, 1, 0, 0]
print(model_accuracy(predictions, actual_values))
In LabEx Python learning environments, these practical examples demonstrate the versatility of float formatting across various domains.