gpt4 book ai didi

java - 使用 printf 的 0 填充问题

转载 作者:行者123 更新时间:2023-11-30 11:04:21 26 4
gpt4 key购买 nike

我正在格式化一个变量。我正在尝试添加 0 填充,但遇到了运行时问题

当我删除左对齐符号“-”时,我可以添加填充,但好像我不能同时添加两者。

代码如下:

  int i4 = 1000;
System.out.printf("Format with position and spacing and left justify and locale separator and 0 padding");
System.out.printf("%1$-,7d \n", i4); //Runs fine
System.out.printf("%1$-,07d \n", i4); //Run time error

编辑:

在运行时我得到:IllegalFormatFlagsException:

Exception in thread "main" java.util.IllegalFormatFlagsException: Flags = '-0,'

有什么建议吗?

最佳答案

我不认为这是可能的。这两个概念不能一起工作。

  • 如果你使用 "%07d"填充零,那么你会得到"001,000"即 7 个​​字符。
  • 在相同格式宽度 7 中左对齐相同数字 001,000 无效,答案仍为“001,000”

如果您想以更大的格式宽度左对齐 1,000,您可以分两步完成...

System.out.printf("Result=\"%-12s\"\n", String.format("%,07d", i4));

输出

Result="001,000     "     

关于java - 使用 printf 的 0 填充问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060412/

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