面试用的数字转汉字的程序

public class IntToChinese {
        protected static final String[] UNITS = { "", "十", "百", "千", 
                                                    "万", "十", "百", "千", 
                                                    "亿", "十", "百", "千", 
                                                 }; 

        protected static final String[] NUMS = {  "零","壹", "贰", "叁", "肆", "伍", 
                                                      "陆", "柒", "捌", "玖", 
                                                }; 

        /** 
         *  数字转换成中文汉字 
         *  @param value  转换的数字 
         *  @return 返回数字转后的汉字字符串 
         */ 
        public static String translate(int value) { 
            //转译结果 
            String result = ""; 

            int len=0;
            while(true){
                result=NUMS[value]+UNITS[len]+result;

                value=value/10;
                len++;
                if(value<1)
                    break;
            }
            result = result.replaceAll("零[十, 百, 千]", "零"); 
            result = result.replaceAll("零+", "零"); 

            result = result.replaceAll("零([万, 亿])", "$1"); 

            result = result.replaceAll("亿万", "亿");   //亿万位拼接时发生的特殊情况 

            if (result.startsWith("壹十")) 
                result = result.substring(1); 

            if(result.endsWith("零")) 
                result = result.substring(0, result.length() - 1); 

            return result; 
        } 

        public static void main( String[] args ) { 
            System.out.println( IntToChinese.translate(1200401)); 
        } 
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×