将数字用中文读取出来

数字转换成中文

针对财务数据将金额数据转换成大写,在网上有许多例子,总觉得有更简朴的体式格局完成,下面是详细的源码和探讨。假如疑问,或更好的发起迎接留言,配合进修。

源码

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位数,假如更大的数据可举行修改。

 numToZh_cn( 100400 ) // 壹拾万零肆佰零元整
    原文作者:心语花束
    原文地址: https://segmentfault.com/a/1190000019057650
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞