Java String Pad Zero zeroPad(String s, int fieldLength)

Here you can find the source of zeroPad(String s, int fieldLength)

Description

Prepend the given string with zeros.

License

Apache License

Parameter

Parameter Description
s the given string
fieldLength desired total field length including the string

Return

a string front padded with zeros.

Declaration

public static final String zeroPad(String s, int fieldLength) 

Method Source Code

//package com.java2s;
/*/*  w w w  . j  a v  a  2  s .c o  m*/
 * Copyright 2015, Yahoo! Inc.
 * Licensed under the terms of the Apache License 2.0. See LICENSE file at the project root for terms.
 */

public class Main {
    /**
     * Prepend the given string with zeros.
     * @param s the given string
     * @param fieldLength desired total field length including the string
     * @return a string front padded with zeros.
     */
    public static final String zeroPad(String s, int fieldLength) {
        char[] chArr = s.toCharArray();
        int sLen = chArr.length;
        if (sLen < fieldLength) {
            char[] out = new char[fieldLength];
            int zeros = fieldLength - sLen;
            for (int i = 0; i < zeros; i++) {
                out[i] = '0';
            }
            for (int i = zeros; i < fieldLength; i++) {
                out[i] = chArr[i - zeros];
            }
            return String.valueOf(out);
        }
        return s;
    }
}

Related

  1. zeroPad(final String s, final int fieldLength)
  2. zeroPad(String encodeString, int padding)
  3. zeroPad(String encodeString, int padding)
  4. zeropad(String number, int size)
  5. zeropad(String s, int i)
  6. zeropad(String s, int len)
  7. zeropad(String s, int len)
  8. zeroPad(String s, int len)