java数字转换为字符串,长度不够前面补0

来源:互联网 发布:云计算有培训班吗 编辑:程序博客网 时间:2024/06/02 17:42

1、 第一种字符串补0
public static String addZeroForNum(String str, int strLength) {
    int strLen = str.length();
    StringBuffer sb = null;
     while (strLen < strLength) {
           sb = new StringBuffer();
           sb.append("0").append(str);// 左补0
        // sb.append(str).append("0");//右补0
           str = sb.toString();
           strLen = str.length();
     }
    return str;
}


2、数字流水号长度不够补0方法
public static String codeAddOne(String code, int len){
   Integer intHao = Integer.parseInt(code);
   intHao++;
   String strHao = intHao.toString();
   while (strHao.length() < len) {
       strHao = "0" + strHao;
     }
   return strHao;
}


3、用java中的DecimalFormat,可以简化:


// 流水号加1后返回,流水号长度为15
private static final String STR_FORMAT = "000000000000"; 
public static String haoAddOne(String liuShuiHao){
    Integer intHao = Integer.parseInt(liuShuiHao);
    intHao++;
    DecimalFormat df = new DecimalFormat(STR_FORMAT);
    return df.format(intHao);
}
0 0
原创粉丝点击