用js實現小寫金額轉大寫的方法

王铁柱6發表於2024-11-26
function amountToChinese(amount) {
  if (typeof amount !== 'number' && typeof amount !== 'string') {
    return '輸入金額格式不正確';
  }

  amount = String(amount);
  if (!/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/.test(amount)) {
    return '輸入金額格式不正確';
  }

  const unit = '仟佰拾億仟佰拾萬仟佰拾元角分';
  const str = '零壹貳叄肆伍陸柒捌玖';
  let newAmount = amount.replace(/^0+/, ''); // 去除前面的0

  if (newAmount === '') {
    return '零元整';
  }

  let fraction = ''; // 處理小數部分
  if (newAmount.indexOf('.') !== -1) {
    const parts = newAmount.split('.');
    newAmount = parts[0];
    fraction = parts[1];
    if (fraction.length === 1) {
      fraction += '0';
    }
  } else {
    fraction = '00';
  }

  let chineseStr = '';
  let unitIndex = unit.length - 1;

  for (let i = newAmount.length - 1; i >= 0; i--) {
    if (newAmount[i] === '0') {
      if (chineseStr.charAt(0) !== '零') {
        chineseStr = '零' + chineseStr;
      }
    } else {
      chineseStr = str.charAt(parseInt(newAmount[i])) + unit.charAt(unitIndex) + chineseStr;
    }
    unitIndex--;
  }

  // 去除多餘的零
  chineseStr = chineseStr.replace(/零(仟|佰|拾|角)/g, '零').replace(/(零)+/g, '零');
  chineseStr = chineseStr.replace(/零(萬|億)/g, '$1');
  chineseStr = chineseStr.replace(/億萬/g, '億');
  chineseStr = chineseStr.replace(/^零+/g, '');  // 去掉開頭的零
  chineseStr = chineseStr.replace(/零元/, '元');
  chineseStr = chineseStr.replace(/零角零分$/, '整');
  chineseStr = chineseStr.replace(/零[整角分]+/, '整');
  chineseStr = chineseStr.replace(/零角/, '零');
  chineseStr = chineseStr.replace(/零分/, '');
  chineseStr = chineseStr.replace(/元整/, '元'); // 防止'元整'變成'元'

  // 新增小數部分
  if (fraction !== '00') {
    chineseStr += str.charAt(parseInt(fraction[0])) + '角';
    if (fraction[1] !== '0') {
      chineseStr += str.charAt(parseInt(fraction[1])) + '分';
    }
  } else if (!chineseStr.includes('元')) { // 處理整數部分為0的情況
      chineseStr += '元整';
  } else if (!chineseStr.endsWith("整")){
      chineseStr += '整';
  }



  return chineseStr;
}


// 測試用例
console.log(amountToChinese(1234567890.12)); // 壹拾貳億叄仟肆佰伍拾陸萬柒仟捌佰玖拾元壹角貳分
console.log(amountToChinese(0.12)); // 壹角貳分
console.log(amountToChinese(100000000)); // 壹億圓整
console.log(amountToChinese(100000000.00)); // 壹億圓整
console.log(amountToChinese(0)); // 零元整
console.log(amountToChinese(0.0)); // 零元整
console.log(amountToChinese("0")); // 零元整
console.log(amountToChinese("0.0")); // 零元整
console.log(amountToChinese("0.00")); // 零元整
console.log(amountToChinese(100)); // 壹佰元整
console.log(amountToChinese(100.00)); // 壹佰元整
console.log(amountToChinese(100.1));  // 壹佰元壹角
console.log(amountToChinese(1

相關文章