gpt4 book ai didi

java - 用于报告格式的 NumberFormat

转载 作者:行者123 更新时间:2023-12-01 11:36:23 24 4
gpt4 key购买 nike

我正在尝试用 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 文档并用 google 搜索,但似乎找不到解决方案。

最佳答案

当您想要格式化字符串以进行对齐时,使用 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"));
}

结果:

enter image description here

关于java - 用于报告格式的 NumberFormat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29948200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com