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

来源:互联网 发布:罗永浩 支那人 知乎 编辑:程序博客网 时间:2024/06/02 21:14

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



一般的做法是先把流水号转换为数值型,然后此数值加1,再把数值转换为字符串,
长度不够流水号长度时再在前面补0:

//流水号加1后返回
public static String haoAddOne(String liuShuiHao){
    Integer intHao = Integer.parseInt(liuShuiHao);
    intHao++;
    String strHao = intHao.toString();
    while (strHao.length() < liuShuiHao.length())
        strHao = "0" + strHao;
    return strHao;
}

用java中的DecimalFormat,可以简化:

//流水号加1后返回,流水号长度为4
private static final String STR_FORMAT = "0000"; 

public static String haoAddOne(String liuShuiHao){
    Integer intHao = Integer.parseInt(liuShuiHao);
    intHao++;
    DecimalFormat df = new DecimalFormat(STR_FORMAT);
    return df.format(intHao);
}
0 0
原创粉丝点击