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

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

    Found this example... Will test...

    import java.text.DecimalFormat;
    class TestingAndQualityAssuranceDepartment
    {
        public static void main(String [] args)
        {
            int x=1;
            DecimalFormat df = new DecimalFormat("00");
            System.out.println(df.format(x));
        }
    }
    

    Tested this and:

    String.format("%05d",number);
    

    Both work, for my purposes I think String.Format is better and more succinct.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 06:57

    If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

    org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')
    
    0 讨论(0)
  • 2020-11-21 06:59

    You can use Google Guava:

    Maven:

    <dependency>
         <artifactId>guava</artifactId>
         <groupId>com.google.guava</groupId>
         <version>14.0.1</version>
    </dependency>
    

    Sample code:

    String paddedString1 = Strings.padStart("7", 3, '0'); //"007"
    String paddedString2 = Strings.padStart("2020", 3, '0'); //"2020"
    

    Note:

    Guava is very useful library, it also provides lots of features which related to Collections, Caches, Functional idioms, Concurrency, Strings, Primitives, Ranges, IO, Hashing, EventBus, etc

    Ref: GuavaExplained

    0 讨论(0)
  • 2020-11-21 07:05

    Let's say you want to print 11 as 011

    You could use a formatter: "%03d".

    You can use this formatter like this:

    int a = 11;
    String with3digits = String.format("%03d", a);
    System.out.println(with3digits);
    

    Alternatively, some java methods directly support these formatters:

    System.out.printf("%03d", a);
    
    0 讨论(0)
  • 2020-11-21 07:05
    public static String zeroPad(long number, int width) {
       long wrapAt = (long)Math.pow(10, width);
       return String.valueOf(number % wrapAt + wrapAt).substring(1);
    }
    

    The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.

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