Convert 1 to 01

前端 未结 11 1461
逝去的感伤
逝去的感伤 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.

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

    You can do this by

    String.format("%02d", 1)
    
    0 讨论(0)
  • 2021-02-07 05:09

    I think, I should add the link to the official Java documentation on formatting numeric outputs.

    https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

    Sample Snipplet: Prints 00 up to 100

    class Main {
        public static void main(String[] args) {
          for(int i=0;i<=100;i++){
            System.out.println(String.format("%02d", i)); 
          }
        }
    }
    

    Output:

    00
    01
    ...
    10
    ...
    100
    
    0 讨论(0)
  • 2021-02-07 05:09

    Or you could just use printf instead of String.format

     for (int i = 0; i <= 100; i++) {
             System.out.printf("%02d%n",i);
        }
    
    0 讨论(0)
  • 2021-02-07 05:10

    Yet another way

    String text = (num < 10 ? "0" : "") + num;
    

    EDIT: The code is short enough that the JIT can compile it to nothing. ;)

    long start = System.nanoTime();
    for(int i=0;i<100000;i++) {
        for(int num=1;num<100;num++) {
            String text = (num < 10 ? "0" : "") + num;
        }
    }
    long time = System.nanoTime() - start;
    System.out.println(time/99/100000);
    

    prints

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