Java String Pad Zero zeroPadString(String string, int length)

Here you can find the source of zeroPadString(String string, int length)

Description

Pads the supplied String with 0's to the specified length and returns the result as a new String.

License

LGPL

Parameter

Parameter Description
string the original String to pad.
length the desired length of the new padded String.

Return

a new String padded with the required number of 0's.

Declaration

public static final String zeroPadString(String string, int length) 

Method Source Code

//package com.java2s;

public class Main {
    private static final char[] zeroArray = "0000000000000000".toCharArray();

    /**//from  www  . jav a 2 s  .c  om
     * Pads the supplied String with 0's to the specified length and returns the
     * result as a new String. For example, if the initial String is "9999" and
     * the desired length is 8, the result would be "00009999". This type of
     * padding is useful for creating numerical values that need to be stored
     * and sorted as character data. Note: the current implementation of this
     * method allows for a maximum <tt>length</tt> of 16.
     * 
     * @param string
     *            the original String to pad.
     * @param length
     *            the desired length of the new padded String.
     * @return a new String padded with the required number of 0's.
     */
    public static final String zeroPadString(String string, int length) {
        StringBuffer buf = new StringBuffer(length);
        buf.append(zeroArray, 0, length - string.length()).append(string);
        return buf.toString();
    }
}

Related

  1. zeroPadding(String value, int n)
  2. zeroPadLeft(String s, final int len)
  3. zeropadRight(String s, int len)
  4. zeroPadSSN(String ssn)
  5. zeroPadString(String string, int length)
  6. zeroPadString(String string, int length)