Java 工具类:数字左补0

有朋友给出更6的写法:



DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字。

常用符号含义:

0 一个数字
# 一个数字,不包括 0
. 小数的分隔符的占位符

public static void main(String[] args) {
		System.out.println(initString('0', 5));
                //生成五位的字符串
		System.out.println(intToString(45, 5));
                //个数化的数字为45
	}
	
	public static String intToString(int n, int l) {
		DecimalFormat decimalFormat = new DecimalFormat(initString(
				'0', l));
		return decimalFormat.format(n);
	}
	
	public static String initString(char ch, int length) {
		if (length < 0)
			return "";
		char chars[] = new char[length];
		for (int i = 0; i < length; i++)
			chars[i] = ch;
		return new String(chars);
	}

output:
00000
00045

猜你喜欢

转载自lovejavah123.iteye.com/blog/2289261