Convert 1 to 01

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

提交回复
热议问题