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;
    }

}

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM