Convert 1 to 01

前端 未结 11 1477
逝去的感伤
逝去的感伤 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 04:48

    Presumably you mean to store the number in a String.

    Since JDK1.5 there has been the String.format() method, which will let you do exactly what you want:

    String s = String.format("%02d", someNumber);
    

    One of the nice things about String.format() is that you can use it to build up more complex strings without resorting to lots of concatenation, resulting in much cleaner code.

    String logMessage = String.format("Error processing record %d of %d: %s", recordNumber, maxRecords, error);
    

提交回复
热议问题