How can I pad an integer with zeros on the left?

后端 未结 16 2297
南旧
南旧 2020-11-21 06:31

How do you left pad an int with zeros when converting to a String in java?

I\'m basically looking to pad out integers up to 9999

16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 06:46

    No packages needed:

    String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;
    

    This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

提交回复
热议问题