nutpi-chinese-number-format:强大的中文数字格式化 UTS 插件(适配鸿蒙)

2025-06-07 11:20:55
123次阅读
0个评论

nutpi-chinese-number-format:强大的中文数字格式化 UTS 插件(适配鸿蒙)

前言

在移动应用开发中,数字的本地化显示是一个常见需求。特别是在中文环境下,我们经常需要将阿拉伯数字转换为中文数字,或者进行相反的转换。今天为大家介绍一个功能强大的 UTS 插件 —— nutpi-chinese-number-format,它专门解决中文数字格式化的各种需求。

插件概述

nutpi-chinese-number-format 是一个专为 uni-app 和 uni-app x 项目设计的中文数字格式化插件。它基于 UTS(UniApp TypeScript)技术开发,提供了完整的 TypeScript 类型定义,确保开发过程中的类型安全。

🌟 核心特性

  • 双向转换:支持阿拉伯数字与中文数字之间的双向转换
  • 大写支持:支持中文数字大写格式转换(如:壹、贰、叁)
  • 单位处理:智能处理万、亿等中文数字单位
  • 近似表示:支持大数字的近似中文表示
  • 月份转换:支持数字月份转中文月份(包括传统月份名称)
  • 多地区支持:同时支持简体中文(zh-CN)和繁体中文(zh-TW)
  • 跨平台兼容:支持 App(Android/iOS/Harmony)、H5、小程序等多个平台
  • 类型安全:完整的 TypeScript 类型定义

技术架构

UTS 技术优势

该插件采用 UTS(UniApp TypeScript)技术开发,相比传统的 JavaScript 插件具有以下优势:

  1. 性能优化:UTS 编译后的代码性能更接近原生
  2. 类型安全:完整的 TypeScript 支持,减少运行时错误
  3. 跨平台一致性:在不同平台上保持一致的行为
  4. 开发体验:更好的 IDE 支持和代码提示

核心算法设计

插件内部采用了高效的映射表设计:

// 基本数字映射
const NUMBER_MAPS = {
  base: {
    "0": ["0", "0", "零", "〇"],
    "1": ["1", "1", "一", "壹"],
    "2": ["2", "2", "二", "貳", "贰"],
    // ...
  },
  "zh-TW": {
    units: ["", "十", "百", "千"],
    bigUnits: [
      "",
      "萬",
      "億",
      "兆",
      "京",
      "垓",
      "秭",
      "穰",
      "溝",
      "澗",
      "正",
      "載",
    ],
    point: "點",
    uppercase: {
      /* 繁体大写映射 */
    },
  },
  "zh-CN": {
    units: ["", "十", "百", "千"],
    bigUnits: [
      "",
      "万",
      "亿",
      "兆",
      "京",
      "垓",
      "秭",
      "穰",
      "沟",
      "涧",
      "正",
      "载",
    ],
    point: "点",
    uppercase: {
      /* 简体大写映射 */
    },
  },
};

为了优化性能,插件还预计算了反向映射表:

// 预计算反向映射表以优化 toNumber 函数性能
const REVERSE_BASE_MAP: Record<string, string> = {};
for (const numKey in NUMBER_MAPS.base) {
  NUMBER_MAPS.base[numKey].forEach((charVariant) => {
    REVERSE_BASE_MAP[charVariant] = numKey;
  });
}

功能详解

1. 基础数字转换

数字转中文

import { toChinese } from "@/uni_modules/nutpi-chinese-number-format";

// 基础转换
const result1 = toChinese(123); // "一二三"
const result2 = toChinese(123.45); // "一二三點四五"

// 指定地区
const result3 = toChinese(123, "zh-CN"); // "一二三"
const result4 = toChinese(123.45, "zh-CN"); // "一二三点四五"

中文转数字

import { toNumber } from "@/uni_modules/nutpi-chinese-number-format";

const num1 = toNumber("一二三"); // 123
const num2 = toNumber("一二三點四五"); // 123.45
const num3 = toNumber("一萬二千三百四十五"); // 12345

2. 带单位的中文表示

import { toChineseWithUnits } from "@/uni_modules/nutpi-chinese-number-format";

// 自动添加合适的单位
const result1 = toChineseWithUnits(12345); // "一萬二千三百四十五"
const result2 = toChineseWithUnits(12345, "zh-CN"); // "一万二千三百四十五"
const result3 = toChineseWithUnits(123456789); // "一億二千三百四十五萬六千七百八十九"

3. 大写转换

import { toUpperCase } from "@/uni_modules/nutpi-chinese-number-format";

// 转换为大写中文数字
const result1 = toUpperCase("一二三"); // "壹貳參"
const result2 = toUpperCase("一二三", "zh-CN"); // "壹贰叁"

4. 大数字近似表示

import { toChineseApproximate } from "@/uni_modules/nutpi-chinese-number-format";

// 大数字的近似表示
const result1 = toChineseApproximate(123456789); // "一點二億"
const result2 = toChineseApproximate(123456789, {
  locale: "zh-CN",
  precision: 2,
}); // "一点二三亿"

5. 月份转换

import { toChineseMonth } from "@/uni_modules/nutpi-chinese-number-format";

// 简单格式
const month1 = toChineseMonth(10); // "十月"
const month2 = toChineseMonth(11); // "十一月"

// 传统格式
const month3 = toChineseMonth(1, { format: "traditional" }); // "正月"
const month4 = toChineseMonth(12, {
  format: "traditional",
  locale: "zh-CN",
}); // "腊月"

实际应用场景

1. 电商应用中的价格显示

// 在商品详情页显示中文价格
const price = 12888;
const chinesePrice = toChineseWithUnits(price, "zh-CN"); // "一万二千八百八十八"

2. 财务应用中的金额大写

// 发票或收据中的金额大写
const amount = "一万二千三百四十五";
const uppercaseAmount = toUpperCase(amount, "zh-CN"); // "壹万贰仟叁佰肆拾伍"

3. 日期选择器中的月份显示

// 传统日历中的月份显示
const months = [];
for (let i = 1; i <= 12; i++) {
  months.push(toChineseMonth(i, { format: "traditional", locale: "zh-CN" }));
}
// ["正月", "二月", "三月", ..., "腊月"]

4. 数据统计中的大数字展示

// 用户量统计的友好显示
const userCount = 1234567;
const friendlyCount = toChineseApproximate(userCount, {
  locale: "zh-CN",
  precision: 1,
}); // "一点二万"

在 Vue 组件中的完整使用示例

<template>
  <view class="number-demo">
    <view class="section">
      <text class="title">基础转换</text>
      <text>数字 {{ originalNumber }} 转中文:{{ chineseNumber }}</text>
      <text>中文转数字:{{ convertedNumber }}</text>
    </view>

    <view class="section">
      <text class="title">带单位转换</text>
      <text>{{ largeNumber }} → {{ chineseWithUnits }}</text>
    </view>

    <view class="section">
      <text class="title">大写转换</text>
      <text>{{ chineseText }} → {{ uppercaseText }}</text>
    </view>

    <view class="section">
      <text class="title">月份转换</text>
      <text>{{ currentMonth }}月 → {{ chineseMonth }}</text>
      <text>传统格式:{{ traditionalMonth }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import {
  toChinese,
  toChineseWithUnits,
  toNumber,
  toUpperCase,
  toChineseApproximate,
  toChineseMonth,
  type Locales,
} from "@/uni_modules/nutpi-chinese-number-format";

// 响应式数据
const originalNumber = ref(12345);
const largeNumber = ref(123456789);
const chineseText = ref("一二三四五");
const currentMonth = ref(10);

// 计算属性
const chineseNumber = computed(() => toChinese(originalNumber.value, "zh-CN"));

const convertedNumber = computed(() => toNumber("一二三四五"));

const chineseWithUnits = computed(() =>
  toChineseWithUnits(largeNumber.value, "zh-CN")
);

const uppercaseText = computed(() => toUpperCase(chineseText.value, "zh-CN"));

const chineseMonth = computed(() => toChineseMonth(currentMonth.value));

const traditionalMonth = computed(() =>
  toChineseMonth(currentMonth.value, {
    format: "traditional",
    locale: "zh-CN",
  })
);
</script>

性能优化

1. 预计算映射表

插件在初始化时预计算了反向映射表,避免了运行时的重复计算:

// 预计算反向映射表,提升 toNumber 函数性能
const REVERSE_BASE_MAP: Record<string, string> = {};
for (const numKey in NUMBER_MAPS.base) {
  NUMBER_MAPS.base[numKey].forEach((charVariant) => {
    REVERSE_BASE_MAP[charVariant] = numKey;
  });
}

2. 高效的字符串处理

在处理大数字时,插件采用了分组处理的方式,提高了转换效率:

// 按4位进行分组处理,提高大数字处理效率
const groups = numStr
  .split("")
  .reverse()
  .reduce((acc: string[][], digit: string, i: number) => {
    const groupIndex = Math.floor(i / 4);
    if (!acc[groupIndex]) acc[groupIndex] = [];
    acc[groupIndex].unshift(digit);
    return acc;
  }, []);

错误处理和边界情况

1. 输入验证

// toNumber 函数的错误处理
export function toNumber(str: string): number {
  let numberStr = "";
  let hasInvalidChar = false;

  for (const char of str) {
    const digit = REVERSE_BASE_MAP[char];
    if (digit !== undefined) {
      numberStr += digit;
    } else {
      hasInvalidChar = true;
      break;
    }
  }

  if (hasInvalidChar || numberStr.length === 0) {
    return NaN; // 转换失败时返回 NaN
  }

  // 处理多个小数点的情况
  const parts = numberStr.split(".");
  if (parts.length > 1) {
    numberStr = parts[0] + "." + parts.slice(1).join("");
  }

  return Number(numberStr);
}

2. 月份验证

// toChineseMonth 函数的边界检查
export function toChineseMonth(
  month: number,
  options: MonthOptions = {}
): string {
  // 检查月份是否在1到12之间且为整数
  if (month < 1 || month > 12 || !Number.isInteger(month)) {
    return ""; // 无效月份返回空字符串
  }
  // ... 其他处理逻辑
}

安装和配置

1. 通过 uni_modules 安装

  1. nutpi-chinese-number-format 文件夹复制到项目的 uni_modules 目录下
  2. 在 HBuilderX 中重新编译项目

2. 环境要求

  • HBuilderX: 3.6.8 或更高版本
  • uni-app: 支持 Vue 2 和 Vue 3
  • uni-app x: 完全支持
  • 平台支持: App(Android/iOS/Harmony)、H5、小程序等

3. TypeScript 配置

如果你的项目使用 TypeScript,插件提供了完整的类型定义:

// 类型导入
import type {
  Locales,
  Options,
  MonthOptions,
} from "@/uni_modules/nutpi-chinese-number-format";

// 使用类型
const locale: Locales = "zh-CN";
const options: Options = {
  locale: "zh-CN",
  precision: 2,
};

最佳实践

1. 地区设置选择

// 根据用户设备语言自动选择地区
const getLocale = (): Locales => {
  const systemLocale = uni.getSystemInfoSync().language;
  return systemLocale.includes("TW") || systemLocale.includes("HK")
    ? "zh-TW"
    : "zh-CN";
};

const userLocale = getLocale();
const result = toChinese(123, userLocale);

2. 错误处理

// 安全的数字转换
const safeToNumber = (str: string): number | null => {
  const result = toNumber(str);
  return isNaN(result) ? null : result;
};

// 使用示例
const userInput = "一二三";
const number = safeToNumber(userInput);
if (number !== null) {
  console.log(`转换成功: ${number}`);
} else {
  console.log("转换失败,请检查输入格式");
}

3. 性能优化建议

// 对于频繁调用的场景,可以缓存结果
const numberCache = new Map<string, string>();

const cachedToChinese = (num: number, locale: Locales = "zh-CN"): string => {
  const key = `${num}_${locale}`;
  if (numberCache.has(key)) {
    return numberCache.get(key)!;
  }

  const result = toChinese(num, locale);
  numberCache.set(key, result);
  return result;
};

总结

nutpi-chinese-number-format 是一个功能全面、性能优秀的中文数字格式化插件。它不仅提供了丰富的转换功能,还具备以下优势:

  1. 技术先进:基于 UTS 技术,性能接近原生
  2. 功能完整:涵盖了中文数字处理的各种场景
  3. 类型安全:完整的 TypeScript 支持
  4. 跨平台:支持 uni-app 生态的所有平台
  5. 易于使用:简洁的 API 设计,上手容易
  6. 性能优化:预计算映射表,高效的算法实现

无论是开发电商应用、财务系统,还是需要中文本地化的其他应用,这个插件都能为你提供可靠的中文数字格式化解决方案。

联系方式

如有问题或建议,请通过以下方式联系:


本文介绍的 nutpi-chinese-number-format 插件采用 MIT 许可证,欢迎开发者使用和贡献代码。

收藏00

登录 后评论。没有帐号? 注册 一个。