Javascript 实现阿拉伯数字转中文数字

1585364631
2023-11-13 / 0 评论 / 115 阅读 / 正在检测是否收录...

代码(仅适用亿位以下):

function numToChinese(num) {  
    const CN_NUM = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];  
    const CN_UNIT = ['', '十', '百', '千', '万', '十', '百', '千', '亿'];  
    let numStr = String(num);  
    let len = numStr.length;  
    let result = '';  
    if (len === 0) {  
        return '零';  
    }  
    for (let i = 0; i < len; i++) {  
        let n = numStr.charAt(i);  
        let unitIndex = len - i - 1;  
        let numIndex = parseInt(n);  
        let preUnit = CN_UNIT[unitIndex];  
        let preNum = CN_NUM[numIndex];  
        let replaceNum = preNum ? preNum : '';  
        if (unitIndex > 0 && numIndex === 0) {  
            replaceNum = '';  
        } else if (numIndex > 0) {  
            replaceNum = preNum;  
        }  
        result += replaceNum + preUnit;  
    }  
    result = result.replace(/零(千|百|十|)/g, '零$1');
    let matchs = (result.match(/([亿|万|千|百|十]{2,})/g))||[]
    for (const iterator of matchs) {
        result = result.replace(iterator,iterator.slice(0,1) + "零")
    }
    result = result.replace("一十","十")
    return result.endsWith("零") ? result.slice(0,-1) : result;
}

console.log(numToChinese(12));

结果:

十二
0

评论 (0)

取消