44.4 Custom Format Patterns and Applications
Beyond simple numbers, apply formatting patterns to IDs, file sizes, and specialized display needs.
44.4.1 Positive/Negative Subpatterns
DecimalFormat df = new DecimalFormat("#,##0.00;(#,##0.00)");
String s1 = df.format(1234.56); // "1,234.56"
String s2 = df.format(-1234.56); // "(1,234.56)"
Pattern before ; applies to positive, after to negative.
44.4.2 Prefix and Suffix
DecimalFormat df = new DecimalFormat("$#,##0.00");
String s1 = df.format(1234.56); // "$1,234.56"
DecimalFormat df2 = new DecimalFormat("#,##0.00 USD");
String s2 = df2.format(1234.56); // "1,234.56 USD"
44.4.3 File Size Formatting
String formatBytes(long bytes) {
if (bytes < 1024) return bytes + " B";
int exp = (int)(Math.log(bytes) / Math.log(1024));
String unit = "KMGTPE".charAt(exp-1) + "B";
return String.format("%.2f %s", bytes / Math.pow(1024, exp), unit);
}
// formatBytes(1536) -> "1.50 KB"
44.4.4 ID and Code Formatting
// Format integer as zero-padded ID
String formatId(int id) {
return String.format("%08d", id); // "00001234"
}
// Or with DecimalFormat
DecimalFormat idFmt = new DecimalFormat("00000000");
String s = idFmt.format(1234); // "00001234"
44.4.5 Duration Formatting
String formatDuration(long millis) {
long sec = millis / 1000;
long min = sec / 60;
long hr = min / 60;
return String.format("%02d:%02d:%02d", hr, min % 60, sec % 60);
}
// formatDuration(3661000) -> "01:01:01"