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

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

    Here is another way to pad an integer with zeros on the left. You can increase the number of zeros as per your convenience. Have added a check to return the same value as is in case of negative number or a value greater than or equals to zeros configured. You can further modify as per your requirement.

    /**
     * 
     * @author Dinesh.Lomte
     *
     */
    public class AddLeadingZerosToNum {
        
        /**
         * 
         * @param args
         */
        public static void main(String[] args) {
            
            System.out.println(getLeadingZerosToNum(0));
            System.out.println(getLeadingZerosToNum(7));
            System.out.println(getLeadingZerosToNum(13));
            System.out.println(getLeadingZerosToNum(713));
            System.out.println(getLeadingZerosToNum(7013));
            System.out.println(getLeadingZerosToNum(9999));
        }
        /**
         * 
         * @param num
         * @return
         */
        private static String getLeadingZerosToNum(int num) {
            // Initializing the string of zeros with required size
            String zeros = new String("0000");
            // Validating if num value is less then zero or if the length of number 
            // is greater then zeros configured to return the num value as is
            if (num < 0 || String.valueOf(num).length() >= zeros.length()) {
                return String.valueOf(num);
            }
            // Returning zeros in case if value is zero.
            if (num == 0) {
                return zeros;
            }
            return new StringBuilder(zeros.substring(0, zeros.length() - 
                    String.valueOf(num).length())).append(
                            String.valueOf(num)).toString();
        }
    }
    

    Input

    0

    7

    13

    713

    7013

    9999

    Output

    0000

    0007

    0013

    7013

    9999

提交回复
热议问题