关于小写数字转化大写数字(非货币类)

2018-05-09  本文已影响0人  Simple_Learn
var convertNumberToChinese = function(num) {
    if (!/^\d*(\.\d*)?$/.test(num)) {
        alert("Number is wrong!");
        return "Number is wrong!";
    }
    var AA = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    var BB = ["", "十", "百", "千", "万", "亿", "点", ""];
    var a = ("" + num).replace(/(^0*)/g, "").split("."),
    k = 0,
    re = "";
    for (let i = a[0].length - 1; i >= 0; i--) {
        switch (k) {
        case 0:
            re = BB[7] + re;
            break;
        case 4:
            if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0])) re = BB[4] + re;
            break;
        case 8:
            re = BB[5] + re;
            BB[7] = BB[5];
            k = 0;
            break;
        default:
            break;
        }
        if (k % 4 === 2 && a[0].charAt(i + 2) !== 0 && a[0].charAt(i + 1) === 0) re = AA[0] + re;
        if (a[0].charAt(i) !== 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
    }

    if (a.length > 1) {
        //加上小数部分(如果有小数部分)
        re += BB[6];
        for (let i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
    }

    //替换所有无用汉字,直到没有此类无用的数字为止
    while (re.search("零零") != -1 || re.search("零亿") != -1 || re.search("亿万") != -1 || re.search("零万") != -1) {
        re = re.replace("零亿", "亿");
        re = re.replace("亿万", "亿");
        re = re.replace("零万", "万");
        re = re.replace("零零", "零");
    }
    //替换以“一十”开头的,为“十”
    if (re.indexOf("一十") == 0) {
        re = re.substr(1);
    }
    //替换以“零”结尾的,为“”
    if (re.lastIndexOf("零") == re.length - 1) {
        re = re.substr(0, re.length - 1);
    }

    return re;
};


例子如下:

console.png

欢迎指正交流。。。

上一篇下一篇

猜你喜欢

热点阅读