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

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

    Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.

    import java.text.NumberFormat;  
    public class NumberFormatMain {  
    
    public static void main(String[] args) {  
        int intNumber = 25;  
        float floatNumber = 25.546f;  
        NumberFormat format=NumberFormat.getInstance();  
        format.setMaximumIntegerDigits(6);  
        format.setMaximumFractionDigits(6);  
        format.setMinimumFractionDigits(6);  
        format.setMinimumIntegerDigits(6);  
    
        System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
        System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
     }    
    }  
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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<requiredLengthAfterPadding)
        {
            resultString=new String(new char[diff]).replace("\0", "0")+number;
        }        
        System.out.println(resultString);
    
    0 讨论(0)
  • 2020-11-21 07:13

    Here is how you can format your string without using DecimalFormat.

    String.format("%02d", 9)

    09

    String.format("%03d", 19)

    019

    String.format("%04d", 119)

    0119

    0 讨论(0)
提交回复
热议问题