数字转中文大写

const priceNum = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];

function getPriceStr(price) {
  const priceMinType = ['', '拾', '佰', '仟'];
  const temFirstStrArr = price.split('');
  temFirstStrArr.reverse();
  const temStrArr = temFirstStrArr.map((item, index) => {
    if (+item) {
      return priceNum[+item] + priceMinType[index];
    }
    return priceNum[+item];
  });
  temStrArr.reverse();
  return temStrArr.join('').replace(/零+/g, '零').replace(/零$/, '');
}

function priceTransform(price) {
  // '':为了能够识别1000亿
  const priceBigType = ['元', '万', '亿', ''];

  const priceInt = parseInt(price);
  const typeCount = parseInt(String(priceInt).length / 4);
  const remainderCount = String(priceInt).length % 4;
  if (typeCount > priceBigType.length - 2 && remainderCount > 0) {
    return `最大单位为${priceBigType[priceBigType.length - 2]}`;
  }

  let strLast = '整';
  // 角分
  if (priceInt !== price) {
    const priceLastType = ['角', '分'];
    const lastPrice = /\.(\d{1,2})/.exec(price)[1];
    const lastStrArr = lastPrice.split('');
    const temStrArr = lastStrArr.map((item, index) => {
      if (+item) {
        return priceNum[+item] + priceLastType[index];
      }
      return '';
    });
    strLast = temStrArr.join('');
  }

  let strFirst = '';
  let count = 0;
  while (count <= typeCount) {
    const sindex = (remainderCount + (count - 1) * 4) < 0 ? 0 : (remainderCount + (count - 1) * 4);
    const eindex = remainderCount + count * 4;
    const temNum = String(priceInt).substring(sindex, eindex);

    strFirst += getPriceStr(temNum) ? getPriceStr(temNum) + priceBigType[typeCount - count] : '';
    count++;
  }

  return strFirst + strLast;
}


console.log(priceTransform(1283.12))    // 壹仟贰佰捌拾叁元壹角贰分
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ronychen’s blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值