uni-app 中无法使用过滤器实现数字转中文大写,因 Vue 3 已移除 filter 且小程序端不支持;必须封装为纯函数在 JS 层调用,确保跨平台稳定性和财务规范准确性。

uni-app 里不能用过滤器(filter)实现数字转中文大写——不是写法不对,是 filter 在 Vue 3 模式下已被移除,且小程序端(微信、支付宝、字节等)根本不会执行它。
为什么 filter 无法用于数字转中文大写
数字转中文大写(如 1234.56 → 壹仟贰佰叁拾肆元伍角陆分)逻辑复杂,涉及位数判断、零的省略规则、单位映射、小数处理等。这类逻辑:
- 必须在 JS 层完整运行,不能靠模板层管道符
|调用 - uni-app 的
filters对象仅在 Vue 2 模式(main.js中调用Vue.filter)下对 H5 有效,小程序真机完全忽略 - 即使强行在 Vue 2 H5 环境写
{{ num | toChineseCapital }},也无法传参控制“是否含元角分”“是否补零”等关键行为
真正可用的实现方式:封装成纯函数 + 在 setup 或 data 中调用
把转换逻辑封装为独立函数,按需调用,跨平台稳定。推荐结构如下:
const toChineseCapital = (num) => {
if (num == null || isNaN(Number(num))) return '零元整'
const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
const units = ['', '拾', '佰', '仟']
const sections = ['元', '万', '亿']
const decimals = ['角', '分']
<p>let [integer, decimal] = String(Number(num).toFixed(2)).split('.')
integer = integer.replace(/^0+/, '') || '0'</p><p>// 处理小数部分
let result = ''
if (decimal !== '00') {
result += decimal[0] !== '0' ? digits[decimal[0]] + decimals[0] : ''
result += decimal[1] !== '0' ? digits[decimal[1]] + decimals[1] : ''
} else {
result += '整'
}</p><p>// 处理整数部分(从右往左每4位一组)
const groups = []
for (let i = integer.length; i > 0; i -= 4) {
groups.push(integer.slice(Math.max(0, i - 4), i))
}
groups.forEach((group, idx) => {
if (group === '0000') return
let groupStr = ''
for (let j = 0; j < group.length; j++) {
const digit = Number(group[j])
if (digit !== 0) {
groupStr += digits[digit] + units[group.length - 1 - j]
} else if (j < group.length - 1 && Number(group[j + 1]) !== 0) {
groupStr += digits[0]
}
}
if (groupStr) result = groupStr + sections[idx] + result
})</p><p>return result || '零元整'
}使用时直接在 setup() 中调用:
const { proxy } = getCurrentInstance()
const displayAmount = toChineseCapital(1234.56) // → "壹仟贰佰叁拾肆元伍角陆分"或绑定到响应式数据:
const amount = ref(1234.56) const chineseAmount = computed(() => toChineseCapital(amount.value))
容易踩的坑:精度、零、单位连读
手写中文大写最常出错的地方不是逻辑,而是边界 case:
-
toChineseCapital(0)必须返回零元整,不能漏“整”字 -
toChineseCapital(10000)要输出壹万元整,不能变成壹万零元整(中间连续零只保留一个) -
toChineseCapital(0.05)应为伍分,不能出现“零元零伍分” - 浮点数直接传入会触发
0.1 + 0.2 === 0.30000000000000004,务必先Number(val).toFixed(2)统一截断 - 微信小程序低基础库(
)不支持 <code>BigInt,超大整数(如亿元级)建议字符串输入,避免 Number 溢出
真正要落地,别碰 filters,直接用函数。复杂点在于中文大写的语义规则本身,而不是运行环境——这部分没法绕开,得老老实实按财务规范写清楚。


















