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>
复制代码

 

posted @   .Tik  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示