js数字单位用汉字格式化

2018-2-9    分类: 前端资源

js 金钱 钱 格式化

效果:

 

var num=120010101;

function quyi(num1) { //去除亿单位
 return Math.floor((num1 - (Math.floor(num1/100000000))*100000000));
}

if( num/100000000 >=1 ){ //过亿的
 console.log(Math.floor(num/100000000)+'亿'); //显示出亿单位


    //以下是判断亿后面的数是否过万
    if( quyi(num)/10000 >=1 ){
       console.log(Math.floor(quyi(num)/10000)+'万')

       console.log( (quyi(num)- Math.floor(quyi(num)/10000)*10000)+"个" );

    }else{
       console.log(quyi(num));
    }

}else if( (quyi(num))/10000 >=1 ){ //仅仅过万的
   console.log( Math.floor(quyi(num)/10000).toLocaleString()+'万')
   console.log( (quyi(num)- Math.floor(quyi(num)/10000)*10000)+"个" );
}else{ //没过万
   console.log(num);
}

 

 

------------------------------------优化后-----------------------------------

 

调用:

<div id="total_money">

</div>

 

function data_format(num) {
var str='';

//让单位包裹着span
 function company(str) {
   return '<span class="font" style="color:#FF823E;position: relative;top:0px; ">'+str+'</span>';
 }

//让每个数字都包裹这span
 function num_wrap(num) {
   var str='';
   var num_length=num.toString().length;
   for(var i=0;i<num_length;i++){
      str=str+'<span style="background:url(../../img/wap/num_bg.png) no-repeat;background-size:100%;width: 1.78rem;display: inline-block;color: #FF823E;font-size: 1.71rem;text-align: center;margin: 0 2px;position: relative;">'+(num.toString().slice(i, i+1))+'</span>';
   }

   return str;
 }

//去除亿单位
 function quyi(num1) {
   return Math.floor((num1 - (Math.floor(num1/100000000))*100000000));
 }

//补零
 function buling(num1) {
   var str0='';
   var num_length=num1.toString().length;
   for(var i=0;(4-num_length)>i;i++ ){
     str0=str0+'0';
   }
   return str0+num1;
 }

 if( num/100000000 >=1 ){ //过亿的

   str+=num_wrap(Math.floor(num/100000000))+company('亿');

  //以下是判断亿后面的数是否过万
  if( quyi(num)/10000 >=1 ){
    str+=num_wrap(buling(Math.floor(quyi(num)/10000)))+company('万');
    str+=num_wrap(buling(quyi(num)- Math.floor(quyi(num)/10000)*10000))+company('元');
  }else{
   str+=num_wrap('0000')+company('万')+num_wrap(buling(quyi(num)))+company('元');
  }

 }else if( (quyi(num))/10000 >=1 ){ //仅仅过万的
   str+=num_wrap(Math.floor(quyi(num)/10000))+company('万');
   str+=num_wrap(buling((quyi(num)- Math.floor(quyi(num)/10000)*10000)))+company('元')
 }else{ //没过万
   str+=num_wrap(num)+company('元');
 }

 $('#total_money').html(str);
}

data_format(1532136);

 

money_format