如何解决Ionic 3使用currency管道格式化货币时的digitsinfo.match报错?
解决Ionic 3中货币格式化的
digitsinfo.match is not a function错误 你遇到的问题是Angular内置currency管道的参数格式不对导致的——你传递的1.2是数字类型,但这个管道要求digitsInfo参数必须是字符串格式,数字没有match方法,所以才会抛出这个错误。下面给你几种可行的解决办法:
方法1:修正内置管道的参数格式
把digitsInfo改成字符串形式的格式规则,比如巴西雷亚尔常用的两位小数格式,写法是"1.2-2":
<h1>R$ {{item.valor | currency:"BRL":true:"1.2-2" }}</h1>
这里的"1.2-2"表示:
- 整数部分至少1位
- 小数部分最少2位、最多2位
完全符合巴西货币的显示规范。
如果不需要自定义位数,直接省略digitsInfo参数,用默认格式也可以:
<h1>R$ {{item.valor | currency:"BRL":true }}</h1>
方法2:自定义BRL货币管道(更灵活)
有时候内置管道的参数限制比较多,你可以自己写一个专门处理巴西雷亚尔的管道,适配性更强:
- 先在项目里生成管道文件:
ionic generate pipe pipes/brl-currency
- 打开生成的
brl-currency.pipe.ts,替换成以下代码:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'brlCurrency' }) export class BrlCurrencyPipe implements PipeTransform { transform(value: number | string): string { // 先把值转成数字,处理字符串类型的输入 const numValue = typeof value === 'string' ? parseFloat(value) : value; if (isNaN(numValue)) return 'R$ 0,00'; // 使用浏览器原生的Intl API格式化 return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(numValue); } }
- 在你的页面模块(比如
home.module.ts)里声明这个管道:
import { BrlCurrencyPipe } from '../pipes/brl-currency.pipe'; @NgModule({ declarations: [ // ...其他组件/管道 BrlCurrencyPipe ] }) export class HomeModule {}
- 最后在模板里直接使用:
<h1>{{item.valor | brlCurrency}}</h1>
额外注意事项
- 确保
item.valor是数字类型,如果是字符串,要么用自定义管道自动转换,要么在模板里用+号转成数字:{{+item.valor | currency:"BRL":true:"1.2-2" }}
内容的提问来源于stack exchange,提问作者Bruno Aparecido da Silva
相关产品推荐
相关产品推荐

