javaScript 阿拉伯数字转中国读法

107 阅读1分钟

源代码

const $G_CN=[{"base":0,"cn":"零","cn2":"零","py":"líng "},{"base":1,"cn":"壹","cn2":"一","py":"yī "},{"base":1,"cn":"贰","cn2":"二","py":"èr "},{"base":1,"cn":"叁","cn2":"三","py":"sān "},{"base":1,"cn":"肆","cn2":"四","py":"sì "},{"base":1,"cn":"伍","cn2":"五","py":"wǔ "},{"base":1,"cn":"陆","cn2":"六","py":"liù ","desc":"陆 避免多音字选择"},{"base":1,"cn":"柒","cn2":"七","py":"qī "},{"base":1,"cn":"捌","cn2":"八","py":"bā "},{"base":1,"cn":"玖","cn2":"九","py":"jiǔ "},{"base":10,"cn":"拾","cn2":"十","py":"shí "},{"base":100,"cn":"佰","cn2":"佰","py":"bǎi "},{"base":1000,"cn":"仟","cn2":"仟","py":"qiān "},{"base":10000,"cn":"万","cn2":"万","py":"wàn "},{"base":100000000,"cn":"亿","cn2":"亿","py":"yì "},{"base":10000000000000000,"cn":"兆","cn2":"兆","py":"zhào "}];


/**
 * 数字转中国读法  
 */ 
Number.prototype.toCN = function (readKey="cn",i = $G_CN.length - 1, emitLeadingOne = true) {  
    if(this<0){  
        let _fu=(readKey=='py'?'fù ':'负');
        return `${this<0?_fu:''}${Math.abs(this).toCN(readKey,i,emitLeadingOne)}`; 
    }  
    // 小数部分处理:  
    let deciPos = String(this).indexOf('.');  
    if (deciPos >= 0) {  
         let decimal = String(this)
         .substring(deciPos + 1)
         .replace(/\d/g, d => parseInt(d)
         .toCN(readKey,i,emitLeadingOne)); 
         let _dian=(readKey=='py'?'diǎn ':'点');
         return `${Math.floor(this).toCN(readKey,i,emitLeadingOne)}${_dian}${decimal}`;  
    }  
    // 整数部分处理  
    if (this < 10) {  
        return $G_CN[(this)][readKey];  
    }  
    let a = Math.floor(this / $G_CN[i].base);  
    let b = this % $G_CN[i].base;  
    let c = b.toCN(readKey,i - 1, emitLeadingOne && a == 0);  
    if (a > 0) {  
        let d = a.toCN(readKey,i,emitLeadingOne);  
        if (emitLeadingOne && i == 10 && a == 1) {  
          d = '';  
        }  
        if (b > 0) {  
            if (String($G_CN[i].base).length - String(b).length > 1) {  
                return d + $G_CN[i][readKey] + $G_CN[0][readKey] + c;  
            } else {  
                return d + $G_CN[i][readKey] + c;  
            }  
        } else {  
             return d + $G_CN[i][readKey];  
        }  
    } else {  
        return c;  
   }  
 }

使用示例

//默认中文大写
console.log(Number(911).toCN())
//中文小写
console.log(Number(911).toCN("cn2"))
//中文拼音
console.log(Number(911).toCN("py"))

//负数
console.log(Number(-911).toCN())


console.log(Number(9.11).toCN())
console.log(Number(-9.11).toCN("cn2"))
console.log(Number(-9.11).toCN("py"))
console.log(Number('011.01').toCN("py"))