Vue过滤器与React Hook:封装JS金额转大写逻辑
将金额数字转为中文大写(如 123.45 → 壹佰贰拾叁元肆角伍分)的核心逻辑是:按位拆分、映射汉字、处理零和角分。在 Vue 中可通过 filters 封装为全局或局部过滤器;在 React 中可封装为自定义 Hook ,两者本质都是纯函数调用。
Vue 中的 filter 实现
在 Vue 2 项目中,可直接定义一个 toChineseMoney 函数作为过滤器。使用时在模板中通过管道符 | 调用,例如 {{ amount | toChineseMoney }}。该方式适合需要频繁在视图层展示大写金额的表单或报表场景。
过滤器内部需处理整数部分和小数部分。整数部分从右向左每四位一组(万、亿),中间连续零只读一个“零”。小数部分仅保留到分,若为 0 则不显示。注意 Vue 3 已移除 filters,建议改用计算属性或方法。
React 自定义 Hook 封装
在 React 组件中,推荐使用自定义 Hook useChineseMoney 来管理状态转换。将原始数值传入 Hook,返回格式化后的字符串。这样可以在组件渲染时自动更新,且便于单元测试。
function toChineseMoney(num) {
if (num === null || num === undefined || isNaN(num)) return '';
const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const cnIntUnits = ['', '拾', '佰', '仟'];
const cnHalfUnits = ['', '万', '亿'];
const cnDecUnits = ['角', '分'];
let isNegative = false;
if (num < 0) {
isNegative = true;
num = -num;
}
// 处理小数部分
let intPart, decPart;
const str = num.toString();
const dotIndex = str.indexOf('.');
if (dotIndex !== -1) {
intPart = str.substring(0, dotIndex);
decPart = str.substring(dotIndex + 1);
} else {
intPart = str;
decPart = '';
}
// 补齐小数部分
while (decPart.length < 2) {
decPart += '0';
}
// 转换整数部分
let result = '';
let zeroCount = 0;
let unitIndex = 0;
for (let i = intPart.length - 1; i >= 0; i--) {
const digit = parseInt(intPart[i], 10);
if (digit === 0) {
zeroCount++;
} else {
if (zeroCount > 0) {
result = cnNums[0] + result;
}
zeroCount = 0;
result = cnNums[digit] + cnIntUnits[unitIndex % 4] + result;
}
unitIndex++;
if ((unitIndex % 4) === 0 && unitIndex !== 0) {
if (parseInt(intPart.substring(0, i), 10) !== 0) {
result = cnHalfUnits[Math.floor(unitIndex / 4)] + result;
}
}
}
// 处理末尾零
if (result.endsWith('零')) {
result = result.slice(0, -1);
}
// 添加单位
if (intPart.length > 0) {
result += '元';
}
// 转换小数部分
let decResult = '';
for (let i = 0; i < 2; i++) {
const digit = parseInt(decPart[i], 10);
if (digit !== 0) {
decResult += cnNums[digit] + cnDecUnits[i];
}
}
if (decResult === '') {
result += '整';
} else {
result += decResult;
}
if (isNegative) {
result = '负' + result;
}
return result;
}
// 测试用例
console.log(toChineseMoney(123.45)); // 壹佰贰拾叁元肆角伍分
console.log(toChineseMoney(1001.05)); // 壹仟零壹元零伍分
console.log(toChineseMoney(0)); // 零元整
console.log(toChineseMoney(-50.6)); // 负伍拾元陆角
运行上述代码,控制台将输出对应的大写金额字符串。例如输入 1001.05 时,会正确识别中间的零并输出“壹仟零壹元零伍分”。若输入为空或 NaN,则返回空字符串。该函数同时适用于 Vue 过滤器和 React Hook 的内部实现。
Hook 内部应包含完整的转换逻辑,包括对负数、NaN 和空值的边界处理。确保每次输入变化时都能重新计算并返回最新的大写金额字符串,避免缓存导致的显示错误。
同一逻辑下的 零 处理细节
当金额为 1001.05 时,正确输出应为“壹仟零壹元零伍分”,而非“壹仟零零壹元伍分”。关键在于识别连续零的位置,并在非零位之间插入单个“零”。
实现时需遍历每一位数字,记录前一位是否为零。若当前位为零且前一位也为零,则跳过;若当前位为零但前一位非零,则追加“零”。接着检查末尾是否有多余的“零”并去除。此逻辑在 Vue 和 React 中完全复用。
Vue 自定义指令中 binding、arg 和 modifiers 的用法
2026-12-04
Vue和React项目中怎么集成表单验证库(Vuelidate/Yup)
2026-12-04
Vue中动态加载本地js脚本的实现方案
2026-12-04
Vue 的 watch 已经收到新值,为什么 DOM 还是旧的?
2026-12-03
Vue 的 watchEffect 为什么漏掉 await 后读取的值?
2026-12-01





