数字转汉字算法

很不错的算法,学习学习


package test;

public class NumberTransfer {
    public final static String[] chnNumChar = new String[]{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    public final static String[] chnUnitSection = new String[]{"", "万", "亿", "万亿"};
    public final static String[] chnUnitChar = new String[]{"", "十", "百", "千"};
    public static void testNumberToChinese() {
        int[] nums = new int[]{304, 4006, 4000, 10003, 10030, 21010011, 101101101,22111};
        for (int i = 0; i < nums.length; i++) {
            System.out.println(numberToChinese(nums[i]));
        }
    }
    public static String numberToChinese(int num) {
        String strIns;
        String chnStr = "";
        int unitPos = 0;
        boolean needZero = false;
        if (num == 0)
            return "零";
        while (num > 0) {
            strIns = "";
            int section = num % 10000;
            if (needZero) {
                chnStr = chnNumChar[0] + chnStr;
            }
            // 添加节权(万,亿)
            strIns += (section != 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
            chnStr = strIns + chnStr;
            // 以万为单位,求万以内的权位
            chnStr = sectionToChinese(section, chnStr);
            needZero = (section < 1000) && (section > 0);
            num = num / 10000;
            unitPos++;
        }
        return chnStr;
    }
    private static String sectionToChinese(int section, String chnStr) {
        String strIns;
        int unitPos = 0;
        boolean zero = true;
        while (section > 0) {
            int v = section % 10;
            if (v == 0) {
                if (section == 0 || !zero) {
                    zero = true;// zero确保不会出现多个零
                    chnStr = chnNumChar[v] + chnStr;
                }
            } else {
                zero = false;
                strIns = chnNumChar[v]; // 此位置对应等中文数字
                strIns += chnUnitChar[unitPos];// 此位置对应的权位
                chnStr = strIns + chnStr;
            }
            unitPos++;
            section = section / 10;
        }
        return chnStr;
    }
    
    public static void main(String[] args) {
    	testNumberToChinese();
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值