Convert 1 to 01

前端 未结 11 1474
逝去的感伤
逝去的感伤 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);
    
    0 讨论(0)
  • 2021-02-07 04:52

    Try this

    String.format("%02d", num)
    
    0 讨论(0)
  • 2021-02-07 04:57

    One possible solution:

    String.valueOf(number + 100).substring(1);
    
    0 讨论(0)
  • 2021-02-07 04:58

    use number format http://download.oracle.com/javase/6/docs/api/java/text/NumberFormat.html

    0 讨论(0)
  • 2021-02-07 05:05

    Using

    String.format("%02d", num)
    

    Is probably the best option.

    0 讨论(0)
  • 2021-02-07 05:08

    You can't do it just using an int. You'll have to convert between Strings (for display) and back to ints (for calculations). You can use the Java Formatter to format your Strings based on the input.

    0 讨论(0)
提交回复
热议问题