utils公共方法:将数字转为汉字
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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现