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

后端 未结 16 2298
南旧
南旧 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:51

    You need to use a Formatter, following code uses NumberFormat

        int inputNo = 1;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumIntegerDigits(4);
        nf.setMinimumIntegerDigits(4);
        nf.setGroupingUsed(false);
    
        System.out.println("Formatted Integer : " + nf.format(inputNo));
    

    Output: 0001

提交回复
热议问题