当前位置: 首页 > Web前端 > HTML5

读取中文数字

时间:2023-04-05 16:17:50 HTML5

数字成中文将金额数据转为大写为财务数据。网上有很多例子。我总觉得有一种更简单的方法可以实现它。下面是具体的源码和探索。如果大家有什么问题或者更好的建议欢迎留言,一起学习。源代码classNumToZh_cn{numLevel=["","100","100","1000","10000","1000","10000","10000000","100000000","10000000000000000000000000000000000000000000000000"0Th000000"0Th,"万","十","百","千","十亿"]currencyUnit=['corners','cents']numMapToCh={'0':'0','1':'一','2':'二','3':'三','4':'四','5':'武','6':'鲁','7':'七'','8':'8','9':'9'}_test(arr,item,index){constunit=this.numLevel[arr.length-index-1];返回项目==='0'?/(百万|十亿)/.test(单位)?单位:'零':this.numMapToCh[item]+unit;}_dataIntHandle(arr){returnarr.map((item,index)=>this._test(arr,item,index)).join('').replace(/zero+/g,'zero').replace(/零$/,'')+'元素';}_dataDeciHandle(arr){returnarr.map((item,index)=>item==='0'?'':this.numMapToCh[item]+this.currencyUnit[index]).join('');}转换(numStr){numStr=''+数列;if(!/^\d+(\.\d+)?$/.test(numStr.trim()))throw'paramisnotnumber';const[x='',y='']=numStr.split('.');返回this._dataIntHandle(x.split(''))+this._dataDeciHandle(y.split(''))+'whole';}}constnumToZh_cn=newNumToZh_cn();export{NumToZh_cn}源码描述是通过num和中文的映射实现的,避免了传统的循环遍历实现。目前,它支持17位数字。如果数据较大,可以修正。numToZh_cn(100400)//十万四百元