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

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 04:53   11   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 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP