【问题标题】:Save an integer in two digit format in a variable in Java将两位数格式的整数保存在Java中的变量中
【发布时间】:2012-08-04 18:56:03
【问题描述】:

如何在 Java 中以两位数格式存储整数?喜欢我可以设置

int a=01;

并将其打印为01?另外,不只是打印,如果我说int b=a;b 也应该将其值打印为01

【问题讨论】:

  • 整数是整数。 假设没有八进制表示法(在 Java 文字中有)然后 1 = 01 = 001 = .. 您希望将 integer 转换为 String 使用这种格式..
  • 首先,int可以表示比99大得多的值。如果需要这样的表示,请自己制作类。
  • 我想你正在寻找这样的东西:Format an Integer using Java String Format
  • 添加了 [0 的可能副本,但在转换为 int 时不显示为两位数](stackoverflow.com/questions/11850609/…)
  • @Mist4u,你曾经使用过 COBOL 吗? :-D

标签: java numbers


【解决方案1】:

我想这就是你要找的东西:

int a = 1;
DecimalFormat formatter = new DecimalFormat("00");
String aFormatted = formatter.format(a);

System.out.println(aFormatted);

或者,更简单地说:

int a = 1;
System.out.println(new DecimalFormat("00").format(a));

int 只是存储一个数量,01 和 1 代表相同的数量,因此它们的存储方式相同。

DecimalFormat 构建一个字符串,以特定格式表示数量。

【讨论】:

    【解决方案2】:
    // below, %02d says to java that I want my integer to be formatted as a 2 digit representation
    String temp = String.format("%02d", yourIntValue);
    // and if you want to do the reverse
    int i = Integer.parse(temp);
    
    // 2 -> 02 (for example)
    

    【讨论】:

    • 应该是“%02d”而不是“%2d”
    【解决方案3】:

    这是不可能的,因为整数就是整数。但您可以根据需要格式化整数 (DecimalFormat)。

    【讨论】:

      【解决方案4】:

      看看下面的格式,它上面的格式可以为我工作

      System.out.printf("%02d", myNumber)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-10
        • 1970-01-01
        相关资源
        最近更新 更多