import java.text.*; class AlignIntegers { static String align(NumberFormat fmt, int n, int sp) { StringBuffer buf = new StringBuffer(); FieldPosition fpos = new FieldPosition(NumberFormat.INTEGER_FIELD); fmt.format(n, buf, fpos); for (int i = 0; i < sp-fpos.getEndIndex(); ++i) buf.insert(0, ' '); return buf.toString(); } public static void main(String[] args) { NumberFormat fmt = NumberFormat.getInstance(); System.out.println(align(fmt, 10, 6)); System.out.println(align(fmt, 100, 6)); System.out.println(align(fmt, 1000, 6)); System.out.println(align(fmt, 10000, 6)); } } /* Output: 10 100 1,000 10,000 */