首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java -如何使用printf()格式化字符串和整数的混合,以在输出中获得相同的长度?

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

Stack Overflow用户
提问于 2016-05-25 12:30:34
回答 2查看 337关注 0票数 0

我在正确格式化这篇文章时遇到问题:

代码语言:javascript
复制
       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

正确的格式是:

代码语言:javascript
复制
   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

我试过了,它确实有效,但是有没有更好的方法呢?

代码语言:javascript
复制
System.out.printf("%60s", this.getClockType() + " cuchoo clock time [" + time.formattedReportedTime() +
            "], " + "total drift = ");

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

回答 2

Stack Overflow用户

发布于 2016-05-25 14:41:05

这里是来自Caio的答案之外的一小段代码。

代码语言:javascript
复制
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);

输出

代码语言:javascript
复制
   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个字符的左填充字符串width
  • %8s -如上所述,具有8 characters
  • %5.2f的(第二个)参数-(第三个)参数必须为浮点型,其宽度为5个字符,精度为2
票数 2
EN

Stack Overflow用户

发布于 2016-05-25 13:00:12

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37427869

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档