Java - 如何使用printf()格式化字符串和整数的混合以在输出中获得相等的长度?

时间:2016-05-25 04:30:34

标签: java string printf decimalformat

我遇到了正确格式化问题:

       starting       mechanical cuchoo clock time [ 0:00:00], total drift = 0.00 seconds
    after 1 day      mechanical cuchoo clock time [23:59:00], total drift = 60.00 seconds

正确的格式是:

   starting  mechanical cuckoo clock time [ 0:00:00], total drift = 0.00 seconds
after 1 day  mechanical cuckoo clock time [23:59:00], total drift = 60.00 seconds

我试过这个并且它确实有效,但是有更好的方法吗?

System.out.printf("%60s", this.getClockType() + " cuchoo clock time [" + time.formattedReportedTime() +
            "], " + "total drift = ");

System.out.printf("%s", fmt.format(time.getTotalDrift()) + "\n");

2 个答案:

答案 0 :(得分:2)

除了Caio的答案之外,这里还有一个小片段。

String format = 
    "%12s  mechanical cuckoo clock time [%8s], total drift = %5.2f seconds%n";
System.out.printf(format, "starting", "0:00:00", 0.0);
System.out.printf(format, "after 1 day", "23:59:00", 60.0);

输出

   starting  mechanical cuckoo clock time [ 0:00:00], total drift =  0.00 seconds
after 1 day  mechanical cuckoo clock time [23:59:00], total drift = 60.00 seconds
  • %12s - (第一个)参数将被格式化为左边填充的字符串,宽度为12个字符
  • %8s - 如上所述,(第二个)参数包含8个字符
  • %5.2f - (第三个)参数,必须是浮点类型,格式为5个charcaters,精度为2

答案 1 :(得分:0)

您应该检查此link。它是格式化程序类文档,它非常实用!