Java String Pad Zero zeropad(String s, int len)

Here you can find the source of zeropad(String s, int len)

Description

left pad with '0'

License

Open Source License

Parameter

Parameter Description
s - original string
len - desired len

Exception

Parameter Description
ISOException if string's length greater than len

Return

zero padded string

Declaration

public static String zeropad(String s, int len) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from   w  w  w  . j  a v  a2  s .  c o  m
     * left pad with '0'
     * @param s - original string
     * @param len - desired len
     * @return zero padded string
     * @throws ISOException if string's length greater than len
     */
    public static String zeropad(String s, int len) {
        return padleft(s, len, '0');
    }

    /**
     * zeropads a long (performs modulus operation)
     *
     * @param l the long
     * @param len the length
     * @return zeropadded value
     */
    public static String zeropad(long l, int len) {
        return padleft(Long.toString((long) (l % Math.pow(10, len))), len, '0');
    }

    /**
     * pad to the left
     * @param s - original string
     * @param len - desired len
     * @param c - padding char
     * @return padded string
     */
    public static String padleft(String s, int len, char c) {
        String trimedString = s.trim();
        int trimedLength = trimedString.length();
        if (trimedLength > len) {
            throw new IllegalArgumentException("invalid len " + trimedLength + "/" + len);
        }

        StringBuilder d = new StringBuilder(len);
        int fill = len - trimedLength;
        while (fill-- > 0) {
            d.append(c);
        }

        d.append(trimedString);
        return d.toString();
    }
}

Related

  1. zeropad(String number, int size)
  2. zeroPad(String s, int fieldLength)
  3. zeropad(String s, int i)
  4. zeropad(String s, int len)
  5. zeroPad(String s, int len)
  6. zeroPad(String s, int length)
  7. zeroPad(String string, int digits)
  8. zeroPadAfterTo(String hex, int i)
  9. zeroPadding(String str, int len)