JavaScript 实现中文数字转换为阿拉伯数字

参考:https://www.jb51.net/article/86391.htm

注:仅修正 ChineseToNumber() 方法中 number 默认值为1,防止单独的 十 转换为 0

<script type="text/javascript">
    var chnNumChar = {
          零:0,
          一:1,
          二:2,
          三:3,
          四:4,
          五:5,
          六:6,
          七:7,
          八:8,
          九:9
        };
    var chnNameValue = {
          十:{value:10, secUnit:false},
          百:{value:100, secUnit:false},
          千:{value:1000, secUnit:false},
          万:{value:10000, secUnit:true},
          亿:{value:100000000, secUnit:true}
        }

    function ChineseToNumber(chnStr) {
        var rtn = 0;
        var section = 0;
        var number = 1;
        var secUnit = false;
        var str = chnStr.split('');

        for (var i = 0; i < str.length; i++) {
            var num = chnNumChar[str[i]];
            if (typeof num !== 'undefined') {
                number = num;
                if (i === str.length - 1) {
                    section += number;
                }
            } else {
                var unit = chnNameValue[str[i]].value;
                secUnit = chnNameValue[str[i]].secUnit;
                if (secUnit) {
                    section = (section + number) * unit;
                    rtn += section;
                    section = 0;
                } else {
                    section += (number * unit);
                }
                number = 0;
            }
        }
        return rtn + section;
    }

    var str = "五";
    var str1 = "十五";
    var str2 = "二十";
    var str3 = "二十五";
    var str4 = "五百零二";
    console.log(str, " : ", ChineseToNumber(str));
    console.log(str1, " : ", ChineseToNumber(str1));
    console.log(str2, " : ", ChineseToNumber(str2));
    console.log(str3, " : ", ChineseToNumber(str3));
    console.log(str4, " : ", ChineseToNumber(str4));
</script>
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇