金额大写转换(改进版)

export function RMBFitter(n){
  /**金额大写的转换 */
  // var fraction = ['角', '分'];
  var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];
  //var head = n < 0? '欠': '';
  n = Math.abs(n);
  var s = '';
  let nString = n + '';
  if(nString.indexOf('.')>-1){
    nString = nString.split('.');
    nString = nString[1];
    if(nString.length>2){
      alert('请确保输入的值不能超过两位小数,否则无法核算成大写金额');
      return;
    }
    if(nString.length>1){
      let jiao = nString[0];
      let fen = nString[1];
      s = (digit[Number(jiao)] + '角' + digit[Number(fen)]+ '分').replace(/零./, '');
    }else{
      let jiao = nString;
      s = (digit[Number(jiao)] + '角');
    }
  }
  s = s || '整';
  n = Math.floor(n);
  for (var i = 0; i < unit[0].length && n > 0; i++)
  {
      var p = '';
      for (var j = 0; j < unit[1].length && n > 0; j++)
      {
          p = digit[n % 10] + unit[1][j] + p;
          n = Math.floor(n / 10);
      }
      s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;
  }
  var result = s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
  if(result.indexOf('分')>0&&result.indexOf('角')<0){
      result = result.replace(/元/g, '元零');
  }
  return result;
}

 

posted on 2018-12-20 11:43  Mike17  阅读(194)  评论(0编辑  收藏  举报

导航

搜狗