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

后端 未结 16 2541
南旧
南旧 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

    If performance is important in your case you could do it yourself with less overhead compared to the String.format function:

    /**
     * @param in The integer value
     * @param fill The number of digits to fill
     * @return The given value left padded with the given number of digits
     */
    public static String lPadZero(int in, int fill){
    
        boolean negative = false;
        int value, len = 0;
    
        if(in >= 0){
            value = in;
        } else {
            negative = true;
            value = - in;
            in = - in;
            len ++;
        }
    
        if(value == 0){
            len = 1;
        } else{         
            for(; value != 0; len ++){
                value /= 10;
            }
        }
    
        StringBuilder sb = new StringBuilder();
    
        if(negative){
            sb.append('-');
        }
    
        for(int i = fill; i > len; i--){
            sb.append('0');
        }
    
        sb.append(in);
    
        return sb.toString();       
    }
    

    Performance

    public static void main(String[] args) {
        Random rdm;
        long start; 
    
        // Using own function
        rdm = new Random(0);
        start = System.nanoTime();
    
        for(int i = 10000000; i != 0; i--){
            lPadZero(rdm.nextInt(20000) - 10000, 4);
        }
        System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
    
        // Using String.format
        rdm = new Random(0);        
        start = System.nanoTime();
    
        for(int i = 10000000; i != 0; i--){
            String.format("%04d", rdm.nextInt(20000) - 10000);
        }
        System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");
    }
    

    Result

    Own function: 1697ms

    String.format: 38134ms

提交回复
热议问题