44.2 DecimalFormat Patterns
DecimalFormat extends NumberFormat with custom pattern strings for fine-grained control.
44.2.1 Pattern Syntax
0 Digit (shows zero if absent)
# Digit (omits if absent)
. Decimal separator
, Grouping separator
- Minus sign
E Exponent separator (scientific notation)
% Multiply by 100 and show percent
‰ Multiply by 1000 and show per mille
44.2.2 Basic Patterns
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#,##0.00");
String s1 = df.format(1234.5); // "1,234.50"
String s2 = df.format(0.5); // "0.50"
DecimalFormat df2 = new DecimalFormat("#,###.##");
String s3 = df2.format(1234.5); // "1,234.5"
String s4 = df2.format(0.5); // "0.5"
44.2.3 Scientific Notation
DecimalFormat sci = new DecimalFormat("0.00E0");
String s = sci.format(12345); // "1.23E4"
DecimalFormat sci2 = new DecimalFormat("##0.0E0");
String s2 = sci2.format(12345); // "12.3E3"
44.2.4 Percent and Per Mille
DecimalFormat pct = new DecimalFormat("#,##0.00%");
String s1 = pct.format(0.1234); // "12.34%"
DecimalFormat pmille = new DecimalFormat("#,##0.0‰");
String s2 = pmille.format(0.1234); // "123.4‰"
44.2.5 Custom Decimal Symbols
import java.text.DecimalFormatSymbols;
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setGroupingSeparator('_');
symbols.setDecimalSeparator('·');
DecimalFormat df = new DecimalFormat("#,##0.00", symbols);
String s = df.format(1234.56); // "1_234·56"