Practical Examples
Float formatting is essential in various applications, from financial calculations to scientific computing. This section explores practical use cases that demonstrate effective float formatting techniques.
1. Financial Calculation Example
import java.text.DecimalFormat;
public class FinancialCalculator {
public static void main(String[] args) {
float price = 129.99f;
float taxRate = 0.08f;
float totalPrice = price * (1 + taxRate);
DecimalFormat currencyFormat = new DecimalFormat("$#,##0.00");
System.out.println("Original Price: " + currencyFormat.format(price));
System.out.println("Total Price (with tax): " + currencyFormat.format(totalPrice));
}
}
public class ScientificMeasurement {
public static void main(String[] args) {
float temperature = 37.5f;
float humidity = 65.25f;
// Formatting with specific precision
System.out.printf("Body Temperature: %.1f°C%n", temperature);
System.out.printf("Humidity Level: %.2f%%%n", humidity);
}
}
Scenario |
Formatting Technique |
Example |
Currency |
DecimalFormat |
$1,234.56 |
Scientific |
printf() |
37.5°C |
Percentage |
String.format() |
65.25% |
3. Data Visualization Preparation
import java.text.DecimalFormat;
public class DataVisualization {
public static void main(String[] args) {
float[] dataPoints = {12.3456f, 45.6789f, 78.9012f};
DecimalFormat dataFormat = new DecimalFormat("0.00");
System.out.println("Processed Data Points:");
for (float point : dataPoints) {
System.out.println(dataFormat.format(point));
}
}
}
graph TD
A[Raw Float Value] --> B{Formatting Need}
B --> |Currency| C[DecimalFormat with Currency Symbol]
B --> |Scientific| D[Precise Decimal Places]
B --> |Percentage| E[Percentage Representation]
B --> |Data Visualization| F[Consistent Decimal Format]
- Choose appropriate precision for the context
- Consider locale-specific formatting
- Handle potential null or extreme values
At LabEx, we recommend practicing these practical examples to master float formatting in Java applications.