Java實現 整型轉字串,位數不足時可以自動補0
阿新 • • 發佈:2021-05-02
程式碼
public class StringUtil { /** * 整型轉字串並格式化 * @param minSize 最小大小 * @param separator 分隔符 * @param intNums 需要轉化的整數 * @return 字串 */ public static String formatInt(int minSize, String separator, int...intNums) { StringBuilder stringBuilder = new StringBuilder(""); for (int i = 0; i < intNums.length; i++) { if(i != 0) { stringBuilder.append(separator); } String s = String.valueOf(intNums[i]); int zeroNum = minSize - s.length(); if(zeroNum > 0) { appendZeroInHead(stringBuilder, zeroNum); } stringBuilder.append(s); } return stringBuilder.toString(); } private static void appendZeroInHead(StringBuilder sb, int zeroNum) { for (int i = 0; i < zeroNum; i++) { sb.append("0"); } } }
效果
測試1
public static void main(String[] args) {
String s = formatInt(2, "-", 1, 2, 3, 4, 10, 20, 900);
System.out.println(s);
}
結果
測試2
public static void main(String[] args) { String s = formatInt(3, ",", 1, 2, 3, 4, 10, 20, 900); System.out.println(s); }
結果