【问题标题】:How to set the number of digits while printing in Java?用Java打印时如何设置位数?
【发布时间】:2017-04-03 09:28:07
【问题描述】:

我无法真正澄清我在标题中要问的内容。我是一天和一个月的整数。如果月份只有一位,我必须在其前面打印一个 0。

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

这就是它在 C# 中的样子:

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

谢谢。

【问题讨论】:

标签: printing numbers integer number-formatting


【解决方案1】:
int month = 4;
DecimalFormat formater = new DecimalFormat("00");
String month_formated = formater.format(month);

【讨论】:

  • 谢谢!注意:必须导入 java.text.DecimalFormat;
【解决方案2】:

除了提供的the answer Fernando Lahoz(这对于您的情况非常具体:十进制格式),您还可以在 Java 中使用System.out.format,它允许您在打印到 System.out 时指定格式字符串(format 函数但适用于任何PrintStream)。你的情况

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

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

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

可以在here 找到所有格式(字符串、十进制、浮点、日历、日期/时间等)的完整语法。 如果您想快速了解数字格式,可以查看this linkthis link

祝你好运!

【讨论】:

  • 哇,嗯.. 谢谢。我真的没想到一个完整而坚定的答案。
  • 哈哈,我的荣幸 ;)
猜你喜欢
  • 2010-11-08
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多