Format an Integer using Java String Format

前端 未结 3 1942
小鲜肉
小鲜肉 2020-12-07 17:01

I am wondering if it is possible, using the String.format method in Java, to give an integer preceding zeros?

For example:

1 would become 001
2 would be

3条回答
  •  难免孤独
    2020-12-07 17:36

    If you are using a third party library called apache commons-lang, the following solution can be useful:

    Use StringUtils class of apache commons-lang :

    int i = 5;
    StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
    

    As StringUtils.leftPad() is faster than String.format()

提交回复
热议问题