數字金額轉大寫金額

function digitUppercase(price) {
  const fraction = ['角', '分'];
  const digit = ['零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖'];
  const unit = [
    ['元', '萬', '億'],
    ['', '拾', '佰', '仟'],
  ];
  let num = Math.abs(price);
  let s = '';
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * (10 ** index)) % 10] + item).replace(/零./, '');
  });
  s = s || '整';
  num = Math.floor(num);
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = '';
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p;
      num = Math.floor(num / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }

  return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}

用法:javascript

digitUppercase(10); // 壹拾元整
相關文章
相關標籤/搜索