Java字符串格式化长度不足补0

当需要对字符串限定长度,而长度不够时在其前面或后面补充0。下面的代码是在前面补0,注释的哪行代码是在后面补0,根据实际情况选择:

package com.zxh.util;

public class StringUtil {

    //字符串格式化长度不足补0
    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

}

需要传入字符串和限定的长度。

就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
原文地址:https://www.cnblogs.com/zys2019/p/15425867.html