黑马程序员技术交流社区

标题: Java 工具类:数字左补0 [打印本页]

作者: 15670379287    时间: 2016-4-8 21:46
标题: Java 工具类:数字左补0
DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字。

常用符号含义:

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

Java代码  收藏代码
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




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2