1. 程式人生 > >阿拉巴數字轉化為中文大寫

阿拉巴數字轉化為中文大寫

//阿拉伯數字轉換為簡寫漢字
function Arabia_To_SimplifiedChinese(Num) {
    for (let i = Num.length - 1; i >= 0; i--) {
        Num = Num.replace(",", "");  //替換Num中的“,”
        Num = Num.replace(" ", "");  //替換Num中的空格
    };
    if (isNaN(Num)) { //驗證輸入的字元是否為數字
        //alert("請檢查小寫金額是否正確");
        return;
    };
    //字元處理完畢後開始轉換,採用前後兩部分分別轉換
    let part = String(Num).split(".");
    let newchar = "";
    //小數點前進行轉化
    for (let i = part[0].length - 1; i >= 0; i--) {
        if (part[0].length > 10) {
            //alert("位數過大,無法計算");
            return "";
        };  //若數量超過拾億單位,提示
        let tmpnewchar = "";
        let perchar = part[0].charAt(i);
        switch (perchar) {
            case "0":  tmpnewchar = "零" + tmpnewchar;break;
            case "1": tmpnewchar = "一" + tmpnewchar; break;
            case "2": tmpnewchar = "二" + tmpnewchar; break;
            case "3": tmpnewchar = "三" + tmpnewchar; break;
            case "4": tmpnewchar = "四" + tmpnewchar; break;
            case "5": tmpnewchar = "五" + tmpnewchar; break;
            case "6": tmpnewchar = "六" + tmpnewchar; break;
            case "7": tmpnewchar = "七" + tmpnewchar; break;
            case "8": tmpnewchar = "八" + tmpnewchar; break;
            case "9": tmpnewchar = "九" + tmpnewchar; break;
        }
        switch (part[0].length - i - 1) {
            case 0: tmpnewchar = tmpnewchar; break;
            case 1: if (perchar != 0) tmpnewchar = tmpnewchar + "十"; break;
            case 2: if (perchar != 0) tmpnewchar = tmpnewchar + "百"; break;
            case 3: if (perchar != 0) tmpnewchar = tmpnewchar + "千"; break;
            case 4: tmpnewchar = tmpnewchar + "萬"; break;
            case 5: if (perchar != 0) tmpnewchar = tmpnewchar + "十"; break;
            case 6: if (perchar != 0) tmpnewchar = tmpnewchar + "百"; break;
            case 7: if (perchar != 0) tmpnewchar = tmpnewchar + "千"; break;
            case 8: tmpnewchar = tmpnewchar + "億"; break;
            case 9: tmpnewchar = tmpnewchar + "十"; break;
        }
        newchar = tmpnewchar + newchar;
    }
    //替換所有無用漢字,直到沒有此類無用的數字為止
    while (newchar.search("零零") != -1 || newchar.search("零億") != -1 || newchar.search("億萬") != -1 || newchar.search("零萬") != -1) {
        newchar = newchar.replace("零億", "億");
        newchar = newchar.replace("億萬", "億");
        newchar = newchar.replace("零萬", "萬");
        newchar = newchar.replace("零零", "零");
    }
    //替換以“一十”開頭的,為“十”
    if (newchar.indexOf("一十") == 0) {
        newchar = newchar.substr(1);
    }
    //替換以“零”結尾的,為“”
    if (newchar.lastIndexOf("零") == newchar.length - 1) {
        newchar = newchar.substr(0, newchar.length - 1);
    }
    return newchar;
}