Convert 1 to 01

前端 未结 11 1472
逝去的感伤
逝去的感伤 2021-02-07 04:09

I have an int between 1 - 99. How do I get it to always be a double digit, ie: 01, 04, 21?

11条回答
  •  攒了一身酷
    2021-02-07 05:09

    You can do this with NumberFormat:

    NumberFormat format = new NumberFormat();
    format.setMinimumIntegerDigits(2);
    System.out.println(format.format(1));
    

    Note - String.format() is a Java 5 method.

    If you're using Java 5 or above you can do:

    String.format("%02d", 1);

    as mentioned in other answers.

提交回复
热议问题