Java `printf` 中的“%d:%02d”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33466300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:42:02  来源:igfitidea点击:

What is the meaning of "%d:%02d" in `printf`?

java

提问by user34343

I have written the following code to convert hours into minutes. I got some help from the internet but I'm not 100% sure what "%d:%02d" means?

我编写了以下代码将小时转换为分钟。我从互联网上得到了一些帮助,但我不是 100% 确定“%d:%02d”是什么意思?

package time;

public class TimeAssignment {

    public static void main(String[] args) {
        // This program will convert hours into minutes
        int time = 120;
        int hours = time / 60; 
        int minutes = time % 60;
        System.out.printf("%d:%02d", hours, minutes);
    }

}

回答by janos

Even though I'm not 100% sure what “%d:%02d” means

即使我不是 100% 确定“%d:%02d”是什么意思

Here you go:

干得好:

  • %dmeans an integer
  • :is a :
  • %02dmeans an integer, left padded with zeros up to 2 digits.
  • %d表示整数
  • :是一个:
  • %02d表示一个整数,左填充零,最多 2 位。

More info at https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

更多信息请访问https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

回答by Jonathan

These are simply the way of printing the numbers. Look at this post java specifiersto understand what specifiers you are using.

这些只是打印数字的方式。查看这篇文章java 说明符以了解您正在使用哪些说明符。

In simple words, %d is an integer that in your case is "hours" and %02d is an integer that is shown as "xx" taken from the variable "minutes"

简单来说, %d 是一个整数,在您的情况下是“小时”,而 %02d 是一个整数,显示为“xx”,取自变量“分钟”

回答by user4792294

"d" is "decimal" integer, there are also "o" for octal integer and "x"/"X" for hexadecimal integer. The rest is as Janos explained.

“d”是“十进制”整数,还有“o”表示八进制整数,“x”/“X”表示十六进制整数。其余的就像Janos解释的那样。

回答by Nimes

%2d outputs a decimal (integer) number that fills at least 2 character spaces, padded with empty space. And %d is similar to the %2d but it consists only one character space. Learn more from here about this %d, %02d, %f etcE.g.: 5 → " 5", 120 → "120"

%2d 输出一个十进制(整数)数,该数至少填充 2 个字符空格,并用空格填充。%d 与 %2d 类似,但它只包含一个字符空间。 从此处了解有关此 %d、%02d、%f 等的更多信息例如:5 → " 5", 120 → "120"

回答by TruVortex_07

In this question when we are talking about %dwe are talking about the hours, the :is the : on digital clocks, and by the %02dwe mean the minutes padded down with 0s on the left side up to two digits.

在这个问题中,当我们谈论时,%d我们谈论的是小时,:在数字时钟上,%02d我们的意思是分钟用左侧的 0 填充到两位数。

Therefore, %d:%02dmeans hr:min.

因此,%d:%02d意味着hr:min