将数字用中文读取出来

5次阅读

共计 1061 个字符,预计需要花费 3 分钟才能阅读完成。

数字转换成中文

针对财务数据将金额数据转换成大写,在网上有很多例子,总感觉有更简单的方式实现,下面是具体的源码和探究。如果疑问,或更好的建议欢迎留言,共同学习。

源码

class NumToZh_cn {numLevel = [ ""," 拾 "," 佰 "," 仟 "," 万 "," 拾 "," 佰 "," 仟 "," 亿 "," 拾 "," 佰 "," 仟 "," 万 "," 拾 "," 佰 "," 仟 "," 亿 "]
    currencyUnit = ['角', '分']
    numMapToCh = {
        '0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖',
        '0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖',
    }
    _dataIntHandle(arr){return arr.map( ( item, index) => {const unit = this.numLevel[ arr.length - index - 1];
            return item === '0' ? (unit === '万' || unit === '亿') ? unit : '零' : this.numMapToCh[item] + unit;
        }).join('').replace(/ 零 +/g,' 零 ').replace(/ 零 $/,'') + '元';
    }
    _dataDeciHandle(arr){return arr.map( ( item, index) =>   item === '0' ? '': this.numMapToCh[item] + this.currencyUnit[index] ).join('');
    }
    convert(numStr){
        numStr = '' + numStr;
        if(!/^\d+(\.\d+)?$/.test(numStr.trim() ) ) throw 'param is not number';
        const [x='', y=''] = numStr.split('.');
        return this._dataIntHandle(x.split('') ) + this._dataDeciHandle(y.split('') ) + '整';
    }
}
const numToZh_cn = new NumToZh_cn();
export {NumToZh_cn}

源码说明

通过 num 与中文的映射实现,避免了传统的循环遍历的实现方式。目前支持持 17 位数,如果更大的数据可进行修正。

 numToZh_cn(100400) // 壹拾万零肆佰零元整

正文完
 0