简体   繁体   English

用于报告格式的NumberFormat

[英]NumberFormat for report formatting

I'm trying to do a quick report in Java and I'm having issues formatting the numbers. 我正在尝试用Java进行快速报告,但是在格式化数字时遇到了问题。 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: 问题在于数组索引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

I want the index 1 and index 3 parameters to align on the right instead of the left so that my report looks neat. 我希望索引1和索引3参数在右侧而不是在左侧对齐,以便我的报表看起来整洁。

I have read the DecimalFormat and NumberFormat java docs and googled and can't seem to find a solution. 我已经阅读了DecimalFormat和NumberFormat Java文档并用谷歌搜索,但似乎找不到解决方案。

When you want to format strings as far as alignment, using String.format() is sufficient enough for alignment. 当您要格式化字符串以使其尽可能对齐时,使用String.format()足以进行对齐。

References: 参考文献:

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

Java string align to right Java字符串右对齐

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: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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