针对财务数据将金额数据转换成大写,在网上有不少例子,总感受有更简单的方式实现,下面是具体的源码和探究。若是疑问,或更好的建议欢迎留言,共同窗习。学习
class NumToZh_cn { numLevel = [ "", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿" ] currencyUnit = [ '角', '分' ] numMapToCh = { '0': '零', '1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖' } _test( arr, item, index ){ const unit = this.numLevel[ arr.length - index - 1 ]; return item === '0' ? /(万|亿)/.test(unit) ? unit : '零' : this.numMapToCh[ item ] + unit; } _dataIntHandle( arr ){ return arr.map( ( item, index ) => this._test(arr, item, index ) ) .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位数,若是更大的数据可进行修正。this
numToZh_cn( 100400 ) // 壹拾万零肆佰零元整