1. 程式人生 > 實用技巧 >數字金額轉變成大寫漢字金額

數字金額轉變成大寫漢字金額

/**
   * @desc 金額轉換成大寫
   * @param {Number} n 需要轉換成大寫的金額
   * @return {String} 轉換後的大寫中文金額
   * @example convertIntegerToChineseCash('123') =>'壹百貳拾叄元整'
   */
  function convertIntegerToChineseCash(n) {

    let fraction = ['角', '分']
    let digit = ['零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖']
    let unit = [
      ['元', '萬', '億', '萬'],
      ['', '拾', '佰', '仟']
    ]

    n = Math.abs(n)
    n = moneyFormat01(n, 2).replace(/,/g, ''); //!!!需要結合金額格式化函式,也可以註釋掉本行
    console.log("+++++++", n)
    let s = ''
    let k = ''
    if (String(n).indexOf('.') == -1) {
      n = n + '.00'
      k = n.split('.')[1].split('')
    } else {
      k = String(n).split('.')[1].split('')
    }
    // for(let i = 0; i < k.length; i++){
    // 	s +=  (digit[Math.floor(Math.pow(10, i)*10*n) % 10] + fraction[i]).replace(/零./, '')
    // }
    for (let i = 0; i < k.length; i++) {
      s += (digit[k[i]] + fraction[i]).replace(/零./, '')
    }

    s = s || '整'

    n = Math.floor(n)

    for (let i = 0; i < unit[0].length && n > 0; i++) {
      let p = ''
      for (let 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
    }
    return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
  }
  console.log(convertIntegerToChineseCash(120))