5

This is how I left pad a string with zeroes:

String.format("%16s", cardTypeString.trim()).replace(' ', '0');

Is there a better way to do this? I don't like the .replace(' ', '0') part.

Blair Osbay
  • 217
  • 1
  • 4
  • 13

3 Answers3

6

You may use StringUtils from Apache Commons:

StringUtils.leftPad(cardTypeString, 16, '0');
Yevhen Surovskyi
  • 931
  • 11
  • 19
4

Implement you own PadLeft:

public static String padLeft(String value, int width, char pad) {
    if (value.length() >= width)
        return value;
    char[] buf = new char[width];
    int padLen = width - value.length();
    Arrays.fill(buf, 0, padLen, pad);
    value.getChars(0, value.length(), buf, padLen);
    return new String(buf);
}

See IDEONE demo.

Andreas
  • 154,647
  • 11
  • 152
  • 247
3
// Pad with zeros and a width of 10 chars.
String.format("%1$010d", 245)

for more details see https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

Sorry. My fault. This will only work for int, not for String!

Christoph-Tobias Schenke
  • 3,250
  • 1
  • 11
  • 17