Java如何设置打印时的位数?

How to set the number of digits while printing in Java?

我无法真正阐明标题中的问题。我是一天和一个月的整数。如果只有一位数字,我必须在前面打印一个 0 的月份。

例如 04 如果月份 = 4 等等。

在 C# 中应该是这样的:

Console.WriteLine("{0}.{1:00}", day, month);

谢谢。

int month = 4;
DecimalFormat formater = new DecimalFormat("00");
String month_formated = formater.format(month);

除了 Java 中的 provided (which is pretty specific to your case: decimal formating) you can also use System.out.format 允许您在打印到 System.out 时指定格式字符串(format 函数适用于任何 PrintStream 尽管)。你的情况

System.out.format("%2d %2d", day, month)

应该可以解决问题。 %d 用于十进制整数,然后您可以在 'd' 之前指定您想要的任何宽度(在您的情况下为 2)。

如果你想访问形成的字符串供以后使用而不是(只)打印它,你可以使用 String.format。它使用与 System.out.format 相同的格式,但 returns 形成的字符串。

可以找到所有格式(字符串、小数、浮点、日历、date/time、...)的完整语法 here。 如果您想快速了解数字格式,您可以查看 this link or this link

祝你好运!