Here you can find the source of zeropad(String s, int len)
Parameter | Description |
---|---|
s | - original string |
len | - desired len |
Parameter | Description |
---|---|
ISOException | if string's length greater than len |
public static String zeropad(String s, int len)
//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(); } }