如何将人民币数字转为大写

 废话不说,直接上代码,实现传入数字输出人民币大写

       let num="502.40"
      function numTocoggle(num){
      	 var regexp=/^\d+(([.]{1}(\d{0,2}))+){0,1}$/
      	 if(regexp.test(num)){
	        let digital=["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"];
	        let unit=[['元','万', '亿'],['','拾','佰','仟']];
	        let decimalUnit=['角','分']
	        let [key,val]=num.split(".");
	        let str=''
	        let keys=key.split("").reverse()
	        console.log(keys)
	        let result=[]
	        let index=0;
		    while(index<keys.length) {
		       result.push(keys.slice(index,index+=4));
		    }
	        for(let h=result.length-1;h>=0;h--){
	           let numstr=''
	          for(let k=result[h].length-1;k>=0;k--){
	          	if(result[h][k]==0){
	          	  numstr+=digital[result[h][k]]+''	
	          	}else{
	          	  numstr+=digital[result[h][k]]+unit[1][k]	
	          	}
	          	 	 
	          }
	          str+=numstr+unit[0][h]
	        }
	        if(val!=undefined){
	           let valString=val.toString();
	           for(var i=0;i<valString.length;i++){
	           	 str+=(digital[valString[i]]+decimalUnit[i])	
	           }
	        }
          return str; 
         }else{
         	return "请输入正确的数字并保留两位小数";
         }
      }

  

  

posted @ 2019-03-08 15:53  前端守望者  阅读(649)  评论(0编辑  收藏  举报