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

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

    Check my code that will work for integer and String.

    Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code

        int number=2;
        int requiredLengthAfterPadding=4;
        String resultString=Integer.toString(number);
        int inputStringLengh=resultString.length();
        int diff=requiredLengthAfterPadding-inputStringLengh;
        if(inputStringLengh

提交回复
热议问题