utils/numberToChinese.js
// 將四位數以內的數字轉換為中文 function SectionToChinese(section) { const chnNumChar = [ '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' ]; const chnUnitChar = ['', '十', '百', '千']; let str = ''; let zeroFlag = false; let unitPos = 0; while (section > 0) { const v = section % 10; if (v === 0) { if (!zeroFlag && str !== '') { str = chnNumChar[0] + str; // 新增"零" } zeroFlag = true; } else { str = chnNumChar[v] + chnUnitChar[unitPos] + str; zeroFlag = false; } section = Math.floor(section / 10); unitPos++; } return str || chnNumChar[0]; // 如果數字是 0,直接返回 "零" } // 將數字轉換為中文 export function NumberToChinese(num) { if (num === 0) return '零'; // 特殊情況,數字為0直接返回"零" const chnUnitSection = ['', '萬', '億', '萬億', '億億']; let unitPos = 0; let strIns = ''; let chnStr = ''; let needZero = false; // 每四位一組,逐組處理 while (num > 0) { const section = num % 10000; if (needZero) { chnStr = '零' + chnStr; } strIns = SectionToChinese(section); strIns += section !== 0 ? chnUnitSection[unitPos] : chnUnitSection[0]; chnStr = strIns + chnStr; needZero = section < 1000 && section > 0; num = Math.floor(num / 10000); unitPos++; } return chnStr; }
在頁面中使用:
import { NumberToChinese } from '@/utils/numberToChinese';
<template> <el-table :data="tableData"> <el-table-column prop="level" label="預警級別"> <template slot-scope="scope"> <div class="color-block" :style="{ backgroundColor: scope.row.rgb }" > {{ NumberToChinese(scope.row.level) }}級 <!-- 呼叫公共方法 --> </div> </template> </el-table-column> </el-table> </template> <script> import { NumberToChinese } from '@/utils/numberUtils'; // 引入公共方法 export default { data() { return { tableData: [ { level: 1, rgb: '#FF0000' }, { level: 2, rgb: '#00FF00' }, { level: 3, rgb: '#0000FF' }, ], }; }, methods: { NumberToChinese, // 將公共方法掛載到 methods 中 }, }; </script> <style> .color-block { color: white; text-align: center; width: 40px; height: 20px; border-radius: 10px; } </style>