Zero pad the argument until it reach the specified length. - Java java.lang

Java examples for java.lang:String Pad

Description

Zero pad the argument until it reach the specified length.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        long arg = 42;
        int length = 4;
        System.out.println(zeroPad(arg, length));
    }//from   ww  w  .  ja v  a  2 s  .  co  m

    /**
     * Zero pad the argument until it reach the specified length.
     *
     * @param arg
     * the argument to pad
     * @param length
     * the desired length
     * @return a zero-padded string
     */
    public static String zeroPad(final long arg, final int length) {
        String valueString = "" + arg;
        if (valueString.length() > length) {
            throw new IllegalArgumentException(
                    "Long attribute overflow for " + valueString
                            + " (length " + valueString.length() + ")");
        }
        StringBuilder format = new StringBuilder("%0");
        format.append(length).append("d");
        return String.format(format.toString(), arg);
    }
}

Related Tutorials