taylorialcom/ Miscellaneous

Formatting Numbers

The DecimalFormat class can be used to customize the way numbers are represented as strings. If you have an appropriately configured DecimalFormat object, formatter, and double, num, with the value 12345.678, calling formatter.format(num) could produce:

In order to control the format of the output, a pattern is passed to the constructor of DecimalFormat. For a more complete/accurate description of the functionality of the DecimalFormat class refer to the Javadoc. What follows is a number of simple examples.

Digits after the Decimal

DecimalFormat formatter = new DecimalFormat("#.##");
System.out.println(formatter.format(12345.678));
System.out.println(formatter.format(123.4));

produces:

Zero Padding

DecimalFormat formatter = new DecimalFormat("0000.000");
System.out.println(formatter.format(12345.678));
System.out.println(formatter.format(123.4));

produces:

Currency

DecimalFormat formatter = new DecimalFormat("$#,##0.00");
System.out.println(formatter.format(12345.678));
System.out.println(formatter.format(123.4));
System.out.println(formatter.format(0.1234));

produces:

Percentages

DecimalFormat formatter = new DecimalFormat("#,###.##%");
System.out.println(formatter.format(0.678));
System.out.println(formatter.format(123.4111));
formatter = new DecimalFormat("###%");
System.out.println(formatter.format(0.678));
System.out.println(formatter.format(123.4111));

produces: