0

I'm trying to do a quick report in Java and I'm having issues formatting the numbers. Here's what I have now:

MessageFormat lineFormat = new MessageFormat("{0}\t{1,number,#,##0}\t    {2,number,#0}\t\t {3,number,#0.00}");

The problem is that array index 1 (and 3 some) is sometimes hundreds and sometimes thousands and that this setting eliminates the positions, so I have this on the output:

Feb 16, 2015    414     42       9.86
Feb 17, 2015    1,908   81       23.56
Feb 19, 2015    786     43       18.28
Feb 20, 2015    1,331   99       13.44

I want the index 1 and index 3 parameters to align on the right instead of the left so that my report looks neat.

I have read the DecimalFormat and NumberFormat java docs and googled and can't seem to find a solution.

Thom
  • 11,254
  • 22
  • 91
  • 152
  • 1
    Have a look at this http://stackoverflow.com/questions/6080390/java-string-align-to-right – Shar1er80 Apr 29 '15 at 15:38
  • @Shar1er80 Please post the contents as an answer with the link so I can give you credit for the answer. – Thom Apr 29 '15 at 16:52

1 Answers1

1

When you want to format strings as far as alignment, using String.format() is sufficient enough for alignment.

References:

http://www.homeandlearn.co.uk/java/java_formatted_strings.html

Java string align to right

public static void main(String[] args) throws Exception {
    // Prints a number, up to 10 characters right justified
    System.out.println(String.format("%10d", 123456));

    // Prints a number, up to 10 characters left justified
    System.out.println(String.format("%-10d", 123456));

    System.out.println(String.format("%10s", "12345"));
    System.out.println(String.format("%-10s", "12345"));

    // Still prints all characters, but since it exceeds the expected 10 characters it's just printed
    System.out.println(String.format("%10s", "123456789101112"));
}

Results:

enter image description here

Community
  • 1
  • 1
Shar1er80
  • 8,751
  • 2
  • 16
  • 25