用于报告格式化的 NumberFormat

NumberFormat for report formatting

我正在尝试在 Java 中做一份快速报告,但我在格式化数字时遇到了问题。这是我现在拥有的:

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

问题是数组索引 1(和 3 一些)有时是数百,有时是数千,并且此设置消除了位置,所以我在输出中有这个:

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

我希望索引 1 和索引 3 参数右对齐而不是左对齐,这样我的报告看起来就很整洁。

我已经阅读了 DecimalFormat 和 NumberFormat java 文档并进行了谷歌搜索,但似乎找不到解决方案。

当你想格式化字符串尽可能对齐时,使用 String.format() 足以对齐。

参考文献:

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"));
}

结果: