Number formatting is essential for presenting numeric values in a readable and consistent manner across different contexts.
graph TD
A[Number Formatting] --> B[DecimalFormat]
A --> C[String.format()]
A --> D[NumberFormat]
public class StringFormatDemo {
public static void main(String[] args) {
// Basic formatting
System.out.printf("Integer: %d%n", 1234);
// Decimal precision
System.out.printf("Float with 2 decimal places: %.2f%n", 123.4567);
// Width and alignment
System.out.printf("Padded integer: %5d%n", 42);
}
}
import java.text.DecimalFormat;
public class DecimalFormatDemo {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("#,###.##");
// Formatting with thousands separator
System.out.println(formatter.format(1234567.89));
// Custom patterns
DecimalFormat currencyFormat = new DecimalFormat("$#,###.00");
System.out.println(currencyFormat.format(1234.5));
}
}
Format Specifier |
Description |
Example |
%d |
Integer |
1234 |
%f |
Floating-point |
123.456 |
%.2f |
Float with 2 decimals |
123.46 |
%,.2f |
With thousands separator |
1,234.56 |
import java.text.NumberFormat;
import java.util.Locale;
public class LocalizedFormatDemo {
public static void main(String[] args) {
// US Number Format
NumberFormat usFormat = NumberFormat.getInstance(Locale.US);
System.out.println(usFormat.format(1234567.89));
// French Number Format
NumberFormat frFormat = NumberFormat.getInstance(Locale.FRANCE);
System.out.println(frFormat.format(1234567.89));
}
}
import java.text.NumberFormat;
public class SpecialFormatDemo {
public static void main(String[] args) {
// Percentage formatting
NumberFormat percentFormat = NumberFormat.getPercentInstance();
System.out.println(percentFormat.format(0.75));
// Currency formatting
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
System.out.println(currencyFormat.format(1234.56));
}
}
Key Takeaways
- Use appropriate formatting methods based on requirements
- Consider localization for international applications
- Leverage DecimalFormat for custom formatting needs
LabEx recommends practicing these formatting techniques to enhance numeric display in Java applications.