将数目字转为指定长度的字符串,如果位数不够,添加前缀 0
将数字转为指定长度的字符串,如果位数不够,添加前缀 0
呃。。。好象可以用 java.text.DecimalFormat。。。先研究一下这个类。
DecimalFormat 版
呃。。。好象可以用 java.text.DecimalFormat。。。先研究一下这个类。
/** * 将数字转为指定长度的字符串,如果位数不够,添加前缀 0 * @param value * @param length * @return */ private static String i2s(int value, int length) { // System.out.println("value:" + value); // System.out.println("length:" + length); String s = String.valueOf(value); if(s.length()>length) { throw new RuntimeException("length is too short."); } else if(s.length()==length) { return s; } else { char[] cc = new char[length]; int i=0; for(; i<length - s.length(); i++) { cc[i] = '0'; } for(; i<length; i++) { //System.out.println(i); cc[i] = s.charAt(length - i - 1); //这里容易出错:length - i - 1 } return new String(cc); } } private static void testI2s() { for (int i = 0; i < 1050; i++) { System.out.println(i2s(i, 3)); } }
DecimalFormat 版
private static String i2s_02(int value, int length) { //java.util.Formatter //DecimalFormat df = new DecimalFormat("###"); //DecimalFormat df = new DecimalFormat("000"); char[] cc = new char[length]; int i=0; for(i=0; i<length; i++) { //cc[i] = '#'; cc[i] = '0'; } DecimalFormat df = new DecimalFormat( new String(cc) ); String s = df.format(value); if(s.length()>length) { throw new RuntimeException("length is too short."); } return s; } private static void testI2s_02() { for (int i = 0; i < 1050; i++) { System.out.println(i2s_02(i, 3)); } }