将阿拉伯数字转成中文大写的方法

// 数字转成大小写
const toChineseNumber = (num:number) => {
  //  四位四位的进行分割
  const parts = num
    .toString()
    .replace(/(?=(\d{4})+$)/g, ',')
    .split(',')
    .filter(Boolean)

  const map = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const units = ['', '十', '百', '千']
  // 把连续的零给去掉 合并为1个零  当零在末尾的时候去掉
  function _handleZero(str) {
    return str.replace(/零+/g, '零').replace(/零$/, '')
  }
  function _transform(n) {
    let result = ''
    for (let i = 0; i < n.length; i++) {
      const c = map[n[i]]
      let u = units[n.length - i - 1]
      if (c === '零') {
        u = ''
      }
      result += c + u
    }
    result = _handleZero(result)
    return result
  }
  const bigUnits = ['', '万', '亿']
  let result = ''
  for (let i = 0; i < parts.length; i++) {
    const p = parts[i]
    const c = _transform(p)
    const u = bigUnits[parts.length - i - 1]
    if (c === '') {
      result += '零'
      continue
    }
    result += c + u
  }
  result = _handleZero(result)
  return result
}
console.log(toChineseNumber(12345)) // 打印结果 一万二千三百四十五
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值