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

后端 未结 16 2267
南旧
南旧 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 07:05

    public static String zeroPad(long number, int width) {
       long wrapAt = (long)Math.pow(10, width);
       return String.valueOf(number % wrapAt + wrapAt).substring(1);
    }
    

    The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.

提交回复
热议问题