简体   繁体   中英

NumberFormat for report formatting

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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM