import org.apache.commons.lang.StringUtils; import java.text.DecimalFormat; import java.util.regex.Pattern; /** * @version V1.0 * @Title: 数字和字符串长度不够补0 * @ClassName: com.newcapec.util.sys * @Description: 参考-http://blog.sina.com.cn/s/blog_69398ed90102vsmt.html * @Copyright 2016-2017 Powered By 研发中心 * @author: FLY * @date:2017/11/9 7:26 */ public class CommonUtils { /** * 判断字符串是否为数字 */ private static Pattern NUMBER_PATTERN = Pattern.compile("^[-\\+]?[\\d]*$"); /** * 长度为4位 */ private static final String STR_FORMAT = "0000"; /** * @param str * @param strLength * @return java.lang.String * @Title: Java字符串长度不够前面或后面补0 * @methodName: addZeroForNum * @Description: * @author: 王延飞 * @date: 2017-11-08 17:28 */ public static String addZeroForNum(String str, int strLength) { if (StringUtils.isEmpty(str)) { return ""; } 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; } /** * @Title: 数字长度不够,前面补0方法 * @methodName: numPreAddZero * @param num * @param len * @return java.lang.String * @Description: * * @author: 王延飞 * @date: 2017-11-09 7:44 */ public static String numPreAddZero(String num, int len) { boolean isNumeric = NUMBER_PATTERN.matcher(num).matches(); if(!isNumeric){ return "字符串不是数字"; } Integer intHao = Integer.parseInt(num); intHao++; String strHao = intHao.toString(); while (strHao.length() < len) { strHao = "0" + strHao; } return strHao; } /** * @Title: 数字长度不够,前面补0方法【用java中的DecimalFormat】 * @methodName: numPreAddZeroByDecimalFormat * @param num * @return java.lang.String * @Description: * * @author: FLY * @date: 2017-11-09 7:50 */ public static String numPreAddZeroByDecimalFormat(String num) { boolean isNumeric = NUMBER_PATTERN.matcher(num).matches(); if(!isNumeric){ return "字符串不是数字"; } Integer parseInt = Integer.parseInt(num); DecimalFormat df = new DecimalFormat(STR_FORMAT); return df.format(parseInt); } public static void main(String[] args) { String addZeroForNum = addZeroForNum("34", 4); System.out.println("【Java字符串长度不够前面或后面补0】"+addZeroForNum); String codeAddOne = numPreAddZero("12ab", 5); System.out.println("【数字流水号长度不够补0方法】"+codeAddOne); String codeAddOne1 = numPreAddZero("12", 5); System.out.println("【数字流水号长度不够补0方法】"+codeAddOne1); String haoAddOne = numPreAddZeroByDecimalFormat("89"); System.out.println("【用java中的DecimalFormat】"+haoAddOne); } }