如上圖要求數字相加後動態轉換大寫數組
<span>{{addtotal|toChies}}</span>
export default { components: { //Editor }, data() { return {} }, filters: { //局部過濾器 toChies: function(amount) { //形參 // 漢字的數字 const cnNums = ["零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"]; // 基本單位 const cnIntRadice = ["", "拾", "佰", "仟"]; // 對應整數部分擴展單位 const cnIntUnits = ["", "萬", "億", "兆"]; // 對應小數部分單位 const cnDecUnits = ["角", "分"]; // 整數金額時後面跟的字符 const cnInteger = "整"; // 整型完之後的單位 const cnIntLast = "元"; // 最大處理的數字 const maxNum = 9999999999999999.99; // 金額整數部分 let integerNum; // 金額小數部分 let decimalNum; // 輸出的中文金額字符串 let chineseStr = ""; // 分離金額後用的數組,預約義 let parts; if (amount === "") { return ""; } amount = parseFloat(amount); if (amount >= maxNum) { // 超出最大處理數字 return ""; } if (amount === 0) { chineseStr = cnNums[0] + cnIntLast + cnInteger; return chineseStr; } // 轉換爲字符串 amount = amount.toString(); if (amount.indexOf(".") === -1) { integerNum = amount; decimalNum = ""; } else { parts = amount.split("."); integerNum = parts[0]; decimalNum = parts[1].substr(0, 4); } // 獲取整型部分轉換 if (parseInt(integerNum, 10) > 0) { let zeroCount = 0; const IntLen = integerNum.length; for (let i = 0; i < IntLen; i++) { const n = integerNum.substr(i, 1); const p = IntLen - i - 1; const q = p / 4; const m = p % 4; if (n === "0") { zeroCount++; } else { if (zeroCount > 0) { chineseStr += cnNums[0]; } // 歸零 zeroCount = 0; //alert(cnNums[parseInt(n)]) chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]; } if (m === 0 && zeroCount < 4) { chineseStr += cnIntUnits[q]; } } chineseStr += cnIntLast; } // 小數部分 if (decimalNum !== "") { const decLen = decimalNum.length; for (let i = 0; i < decLen; i++) { const n = decimalNum.substr(i, 1); if (n !== "0") { chineseStr += cnNums[Number(n)] + cnDecUnits[i]; } } } if (chineseStr === "") { chineseStr += cnNums[0] + cnIntLast + cnInteger; } else if (decimalNum === "") { chineseStr += cnInteger; } return chineseStr; } }, //計算金額總和保留小數點兩位 computed: { addtotal() { let total = 0; let totalSmall = this.infoData.detail totalSmall.map((item) => { if (item.amount == '') { item.amount = 0; } total += Number(item.amount) }) return total.toFixed(2)//四捨五入保留兩位 } }, }