字符串补0操作

代码如下:

public static void main(String[] args) {
    System.out.println(addZeroForLeft(1001, 6));
    System.out.println(addZeroForLeft("abcd", 6));
}

/**
 * @描述: 整数前面补0
 * @param number 原始整数
 * @param formatLength 指定要格式化的长度
 * @return 补0后的字符串
 */
private static String addZeroForLeft(int number, int formatLength) {
    // 补0操作
    return String.format("%0" + formatLength + "d", number);
}

/**
 * @描述: 字符串前面补0
 * @param str 原始字符串
 * @param formatLength 指定要格式化的长度
 * @return 补0后的字符串
 */
private static String addZeroForLeft(String str, int formatLength) {
    int strLength = str.length();
    if (formatLength > strLength) {
        // 计算实际需要补0长度
        formatLength -= strLength;
        // 补0操作
        str = String.format("%0" + formatLength + "d", 0)   + str;
    }
    return str;
}

效果如下:

001001
00abcd

猜你喜欢

转载自blog.51cto.com/1197822/2399680