把数字转换成中文toChineseNum(12345)

 

把数字转换成中文

toChineseNum(12345); // 一万二千三百四十五

const toChineseNum = (num) => {
    const keys = ["零","一","二","三","四","五","六","七","八","九"];
    const count = ["","十","百","千"];
    var str = "",
        nums = num.toString().split("").reverse();

    nums.map(function(value, index){
        str = keys[value] + 
            (value == 0 ? "" : count[ index > 3 ? index % 4 : index ]) +
            (index == 4 ? "万" : "") +
            str;
    })

    /*
     * 需要去掉的零:
     * 1.后面跟着零的零
     * 2.最后连续的零
     * 3.万前面的零
     */
    return str.replace(/零(?=零)|零$|零(?=万)/g,"");
}

 

posted @ 2018-08-28 17:46  我爱吃小丸子  阅读(485)  评论(0编辑  收藏  举报