中文数字转阿拉伯数字 数字转换

https://www.d5.nz/read/sfdlq/text-part0000_split_030.html

	Map<Character, Integer> chnUnitMap = new HashMap<>();
    Map<Character, Integer> chnNumMap  = new HashMap<>();
    int[] value = {10, 100, 1000, 10000, 100000000};
    boolean[] secUnit = {false, false, false, true, true}; // 万、亿等单位表示 1个section结束,中文4位数为一节
    {
        chnUnitMap.put('十', 0);
        chnUnitMap.put('百', 1);
        chnUnitMap.put('千', 2);
        chnUnitMap.put('万', 3);
        chnUnitMap.put('亿', 4);

        chnNumMap.put('零', 0);
        chnNumMap.put('一', 1);
        chnNumMap.put('二', 2);
        chnNumMap.put('三', 3);
        chnNumMap.put('四', 4);
        chnNumMap.put('五', 5);
        chnNumMap.put('六', 6);
        chnNumMap.put('七', 7);
        chnNumMap.put('八', 8);
        chnNumMap.put('九', 9);
    }

    public int ChineseToNumber(String str) {
        int res = 0;
        int section = 0;        //  节
        int num = 0;            // 数字
        int pos = 0;

        while (pos < str.length()) {
            /*数字还是单位?*/
            if(chnNumMap.containsKey(str.charAt(pos)))  {
                num = chnNumMap.get(str.charAt(pos));
                if (pos == str.length()-1) { // 到最后一个字符了
                    section += num;
                    res = res + section;
                    break;
                }
            }
            else {
                int idx = chnUnitMap.get(str.charAt(pos));
                int unit = value[idx];
                boolean isSecUnit = secUnit[idx];

                if (isSecUnit) { // 是节权说明一个节已经结束  中文4位数为一节  如: 1,0000,0000
                    section = (section + num) * unit;
                    res = res + section;
                    section = 0;
                }
                else {
                    section = section + (num * unit);
                }

                num = 0;

                if (pos == str.length()-1) { // 到最后一个字符了
                    res = res + section;
                    break;
                }
            }
            
            pos++;
        }

        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值