Aligning decimal numbers to the decimal fields

You can use the class FieldPosition and one of the Format classes. FieldPosition keeps track of where a certain part in the formatted string is located. Those parts are dependent on the type of Format class you use and are defined in constants. For example, the class DateFormat contains constants like DAY_OF_WEEK_FIELD or MONTH_FIELD. Likewise, the NumberFormat class contains two constants: INTEGER_FIELD and FRACTION_FIELD. When you invoke the method format, you can supply an instance of FieldPosition which will be filled in with information about the position of the field (beginIndex and endIndex).

Main.java:

import java.text.*;
 
public class Main {
   public static void main(String args[]) {
      double array[] = { 0, 0.1, 1.0, 213.034, 12.43, 12, 0.9832, 4567 };
 
      NumberFormat nf = NumberFormat.getInstance();
      StringBuffer buffer = new StringBuffer();
      for (int i=0; i<array.length; i++) {
         FieldPosition fp = new FieldPosition(NumberFormat.FRACTION_FIELD);
         buffer.setLength(0);
         nf.format(array[i], buffer, fp);
 
         alignInColumn(buffer, fp);
      }
   }
 
   public static void alignInColumn(StringBuffer sb, FieldPosition fp) {
      int col = 10-fp.getBeginIndex();
      if (fp.getBeginIndex() == fp.getEndIndex())
         col--;
 
      for (int i=0; i<col; i++) { 
         System.out.print(' ');
      }
      System.out.println(sb);
   }
}

outputs:

        0
        0.1
        1
      213.034
       12.43
       12
        0.983
    4,567