Preface
In mobile application development, the localized display of numbers is a common requirement. Especially in a Chinese environment, we often need to convert Arabic numerals to Chinese numerals or perform the opposite conversion. Today, I would like to introduce to you a powerful UTS plugin – nutpi-chinese-number-format, which is specifically designed to address various requirements for formatting Chinese numbers.
Plugin Overview
nutpi-chinese-number-format is a Chinese number formatting plugin specifically designed for the uni-app and uni-app x projects. It is developed based on UTS (UniApp TypeScript) technology and provides complete TypeScript type definitions to ensure type safety during the development process.
Core characteristics
- Bidirectional conversion: Supports bidirectional conversion between Arabic numerals and Chinese numerals
- Uppercase support: Supports conversion of Chinese numerals to uppercase format (e.g. One, Two, three)
- Unit processing: Intelligent processing of Chinese digital units such as tens of thousands and billions
- Approximate representation: Supports approximate Chinese representation of large numbers
- Month conversion: Supports conversion from numeric months to Chinese months (including traditional month names)
- ulti-region support: Supports both Simplified Chinese (zh-CN) and Traditional Chinese (zh-TW)
- Cross-platform compatibility: Supports multiple platforms including App (Android/iOS/Harmony), H5 and mini programs
- Type safety: Complete TypeScript type definitions
Development process
We need to create the project in the way shown in the figure first, and then select uniappx and vue3
enter image description here
Next, we can create a new uni_modules plugin. Among them, we select the uts plugin -API plugin.
The following is the process of everyone writing code. It should be noted here that since the connection between this plugin and the platform is not very strong, we just need to create index.uts in the root directory of the plugin to implement my logic.
Technical architecture
Technical advantages of UTS
This plugin is developed using UTS (UniApp TypeScript) technology and has the following advantages compared with traditional JavaScript plugins:
- Performance optimization: The performance of the code compiled by UTS is closer to native
- Type safety: Full TypeScript support to reduce runtime errors
- Cross-platform consistency: maintaining consistent behavior across different platforms
- Development experience: Better IDE support and code hints
Core algorithm design
The plugin adopts an efficient mapping table design internally:
// Basic number mapping
const NUMBER_MAPS = {
base: {
"0": ["0", "0", "零", "〇"],
"1": ["1", "1", "一", "壹"],
"2": ["2", "2", "二", "貳", "贰"],
// ...
},
"zh-TW": {
units: ["", "十", "百", "千"],
bigUnits: [
"",
"萬",
"億",
"兆",
"京",
"垓",
"秭",
"穰",
"溝",
"澗",
"正",
"載",
],
point: "點",
uppercase: {
/* Traditional uppercase mapping */
},
},
"zh-CN": {
units: ["", "十", "百", "千"],
bigUnits: [
"",
"万",
"亿",
"兆",
"京",
"垓",
"秭",
"穰",
"沟",
"涧",
"正",
"载",
],
point: "点",
uppercase: {
/* Simplified Capital Letter mapping */
},
},
};
To optimize performance, the plugin also expects to calculate the reverse mapping table:
// Pre-calculate the reverse mapping table to optimize the performance of the toNumber function
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;
});
}
Detailed Explanation of Functions
1. Basic digital conversion
Digital to Chinese
import { toChinese } from "@/uni_modules/nutpi-chinese-number-format";
// Basic transformation
const result1 = toChinese(123); // "一二三"
const result2 = toChinese(123.45); // "一二三點四五"
// Designated area
const result3 = toChinese(123, "zh-CN"); // "一二三"
const result4 = toChinese(123.45, "zh-CN"); // "一二三点四五"
Chinese to digital
import { toNumber } from "@/uni_modules/nutpi-chinese-number-format";
const num1 = toNumber("一二三"); // 123
const num2 = toNumber("一二三點四五"); // 123.45
const num3 = toNumber("一萬二千三百四十五"); // 12345
2. Chinese representation with units
import { toChineseWithUnits } from "@/uni_modules/nutpi-chinese-number-format";
// Automatically add appropriate units
const result1 = toChineseWithUnits(12345); // "一萬二千三百四十五"
const result2 = toChineseWithUnits(12345, "zh-CN"); // "一万二千三百四十五"
const result3 = toChineseWithUnits(123456789); // "一億二千三百四十五萬六千七百八十九"
- Capitalization conversion
import { toUpperCase } from "@/uni_modules/nutpi-chinese-number-format";
// Convert to capital Chinese numerals
const result1 = toUpperCase("一二三"); // "壹貳參"
const result2 = toUpperCase("一二三", "zh-CN"); // "壹贰叁"
- Approximate representation of large numbers
import { toChineseApproximate } from "@/uni_modules/nutpi-chinese-number-format";
// Approximate representation of large numbers
const result1 = toChineseApproximate(123456789); // "一點二億"
const result2 = toChineseApproximate(123456789, {
locale: "zh-CN",
precision: 2,
}); // "一点二三亿"
- Month conversion
import { toChineseMonth } from "@/uni_modules/nutpi-chinese-number-format";
// Simple format
const month1 = toChineseMonth(10); // "十月"
const month2 = toChineseMonth(11); // "十一月"
// Traditional format
const month3 = toChineseMonth(1, { format: "traditional" }); // "正月"
const month4 = toChineseMonth(12, {
format: "traditional",
locale: "zh-CN",
}); // "The twelfth lunar month"
Actual application scenarios
- Price display in e-commerce applications
// Display the Chinese price on the product detail page
const price = 12888;
const chinesePrice = toChineseWithUnits(price, "zh-CN"); // "一万二千八百八十八"
- The amount in the financial application should be capitalized
// The amount in the invoice or receipt is capitalized
const amount = "一万二千三百四十五";
const uppercaseAmount = toUpperCase(amount, "zh-CN"); // "壹万贰仟叁佰肆拾伍"
- Month display in the date picker
// The month display in the traditional calendar
const months = [];
for (let i = 1; i <= 12; i++) {
months.push(toChineseMonth(i, { format: "traditional", locale: "zh-CN" }));
}
// ["正月", "二月", "三月", ..., "腊月"]
- Large number display in data statistics
// Friendly display of user volume statistics
const userCount = 1234567;
const friendlyCount = toChineseApproximate(userCount, {
locale: "zh-CN",
precision: 1,
}); // "One hundred and twenty thousand"
A complete usage example in Vue components
<template>
<view class="number-demo">
<view class="section">
<text class="title">Basic transformation</text>
<text>Digital {{ originalNumber }} Convert to Chinese:{{ chineseNumber }}</text>
<text>Chinese to digital:{{ convertedNumber }}</text>
</view>
<view class="section">
<text class="title">With unit conversion</text>
<text>{{ largeNumber }} → {{ chineseWithUnits }}</text>
</view>
<view class="section">
<text class="title">Capitalization conversion</text>
<text>{{ chineseText }} → {{ uppercaseText }}</text>
</view>
<view class="section">
<text class="title">Month conversion</text>
<text>{{ currentMonth }}月 → {{ chineseMonth }}</text>
<text>Traditional format:{{ 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";
// Responsive data
const originalNumber = ref(12345);
const largeNumber = ref(123456789);
const chineseText = ref("一二三四五");
const currentMonth = ref(10);
// computational attribute
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>
- Pre-computed mapping table
The plugin pre-calculates the reverse mapping table during initialization, avoiding repetitive calculations at runtime:
// Pre-compute the reverse mapping table to enhance the performance of the toNumber function
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;
});
}
- Efficient string processing
When dealing with large numbers, the plugin adopts a group processing method, which improves the conversion efficiency:
// Group and process by 4 bits to improve the efficiency of processing large numbers
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;
}, []);
Error handling and boundary situations
- Input validation
// Error handling of the toNumber function
exportfunction 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) {
returnNaN; // Return NaN when the conversion fails
}
// Handle the situation of multiple decimal points
const parts = numberStr.split(".");
if (parts.length > 1) {
numberStr = parts[0] + "." + parts.slice(1).join("");
}
returnNumber(numberStr);
}
- Monthly verification
// Boundary check of the toChineseMonth function
export function toChineseMonth(
month: number,
options: MonthOptions = {}
): string {
// Check whether the month is between 1 and 12 and is an integer
if (month < 1 || month > 12 || !Number.isInteger(month)) {
return ""; // An invalid month returns an empty string
}
// ... Other processing logics
}
Installation and configuration
1. Install through uni_modules
- Copy the “nutpi-chinese-number-format” folder to the “uni_modules” directory of the project
- Recompile the project in HBuilderX
2. Environmental requirements
- HBuilderX: 3.6.8 or later version
- uni-app: Supports Vue 2 and Vue 3
- uni-app x: Fully supported
- Platform support: App (Android/iOS/Harmony), H5, mini-programs, etc
3. TypeScript configuration
If your project uses TypeScript, the plugin provides complete type definitions:
// Type import
import type {
Locales,
Options,
MonthOptions,
} from "@/uni_modules/nutpi-chinese-number-format";
// Use type
const locale: Locales = "zh-CN";
const options: Options = {
locale: "zh-CN",
precision: 2,
};
Best practice
1. Region Settings selection
// Automatically select the region based on the language of the user's device
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. Error handling
// Secure digital conversion
const safeToNumber = (str: string): number | null => {
const result = toNumber(str);
returnisNaN(result) ? null : result;
};
// Usage example
const userInput = "一二三";
constnumber = safeToNumber(userInput);
if (number !== null) {
console.log(`Conversion successful: ${number}`);
} else {
console.log("Conversion failed. Please check the input format");
}
3. Performance optimization suggestions
// For scenarios with frequent calls, the results can be cached
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;
};
Summary
nutpi-chinese-number-format is a comprehensive and high-performance Chinese number formatting plugin. It not only offers rich conversion functions, but also has the following advantages:
- Advanced technology: Based on UTS technology, its performance is close to native
- Complete functions: It covers various scenarios of Chinese digital processing
- Type safety: Full TypeScript support
- Cross-platform: Supports all platforms of the uni-app ecosystem
- Easy to use: The simple API design makes it easy to get started
- Performance optimization: Pre-computed mapping table, efficient algorithm implementation
Whether it’s developing e-commerce applications, financial systems, or other applications that require Chinese localization, this plugin can provide you with a reliable solution for formatting Chinese numbers.
Thank you, stackoverflow, for allowing my article to be displayed



