The Java Program: Decimal.java

  1 import java.text.DecimalFormat;
  2 
  3 class Decimal {
  4 
  5    public static void main(String[] args) {
  6       final String pat = "#,#00.0#;(#,#00.0#)";
  7       double [] nums = {
  8          12345678, 1234.5678, 1234.567, 1234.56, 1234.5, 1234.,  123.,  1,
  9         -12345678,-1234.5678,-1234.567,-1234.56,-1234.5,-1234., -123., -1
 10       };
 11 
 12       final DecimalFormat df = new DecimalFormat(pat);
 13 
 14       // Print the pattern.
 15       System.out.println("Pattern");
 16       System.out.println(df.toPattern());
 17       System.out.println();
 18 
 19       // Print the numbers.
 20       System.out.print(fmt ("Original double", 20));
 21       System.out.println("Formatted string");
 22   
 23       for (int i=0; i < nums.length; i++) {
 24          System.out.print (fmt (new Double(nums[i]).toString(), 20));
 25          System.out.println(df.format(nums[i]));
 26       }
 27    }
 28 
 29    // left justify a string by padding with blanks
 30    private final static String padding = "                                   ";
 31    public static String fmt (String s, int width) {
 32       final int n = Math.max (width-s.length(), 0);
 33       return (s+padding.substring(0,n));
 34    }
 35 }