【问题标题】:JAVA: Multiple formats for System.out.formatJAVA:System.out.format 的多种格式
【发布时间】:2016-01-26 08:52:27
【问题描述】:

我正在尝试将我的双整数格式化为间隔,并在末尾有两个 0 而不是一个。

我的代码:

System.out.format(%-10s", double);

这非常适合我正在做的事情。

然后我用

System.out.format(%.2f", double);

正确显示带有两个整数的双精度。

我的问题是我似乎无法将这两种格式化程序结合起来处理一个双精度。例如:

System.out.format(%-10s %.2f", double);

显示类似“{the proper space} double.00”的内容

当我只使用一个时,它们可以完美地工作,但我似乎无法弄清楚如何在同一个双人上同时使用这两个。抱歉,如果我含糊不清,我的时间非常有限,需要尽快完成。

【问题讨论】:

  • 您是否应该考虑改用 DecimalFormatter 类/
  • 类似System.out.format("%10.2f%n", 1d);?
  • @MadeProgrammer 运行时出现错误
  • @Nambari 我实际上是在 DecimalFormat atm 上使用“#0.00”作为解决方法,以便实际上可以工作。我只是想看看是否可以仅使用格式来做到这一点。感谢您尝试提供帮助!
  • AFAIK 系统格式是非常通用的实现,您正在寻找的可能不存在。除非您对 DecimalFormatter 有限制,否则我会说随它去吧。

标签: java string format


【解决方案1】:

这段代码...

System.out.format("<%-10s>\n", "a");
System.out.format("<%10f>\n", 0.2);
System.out.format("<%-10f>\n", 0.2);
System.out.format("<%10.2f>\n", 0.2);
System.out.format("<%-10.2f>\n", 0.2);

...显示...

<a         >
<  0,200000>
<0,200000  >
<      0,20>
<0,20      >

...是你要找的最后一个吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多