【问题标题】:Angular2+ currency pipe doesn't work if a number is 1000+如果数字为 1000+,则 Angular2+ 货币管道不起作用
【发布时间】:2021-11-10 06:46:18
【问题描述】:

我有一个组件,我在其中计算总价并使用主题 + 货币管道显示总价。 我的值超过 1000+ 时出现错误:

 InvalidPipeArgument: '1,004.33 is not a number' for pipe 'CurrencyPipe'

我的组件 ts 文件:

    export class AppComponent  {
      private PRICE: number = 14.99;
      private AMOUNT: number = 1;
      private totalAmount: number = 0;
      public totalPrice$: BehaviorSubject<number> = new BehaviorSubject<number>(0);
    
      public onCalcPrice(): void {
        let price = parseFloat((this.AMOUNT * this.PRICE).toFixed(2));
        this.totalAmount+=price
        this.totalPrice$.next(this.totalAmount);
      }
    }

我的组件 html 文件:

    <p>
      {{totalPrice$ | async | number | currency: "USD"}}
    </p>
    <div>
      <button type="button" (click)="onCalcPrice()">increase price amount</button>
    </div>

stackblitz

【问题讨论】:

  • 移除管道number?
  • 好吧,看起来它正在工作)。那么,这有什么意义呢?
  • number 管道将您的输入作为1004.3300000000005 并将您的号码格式化为1,004.33。这将在第一阶段传递给Currency 管道,货币管道本身会尝试检查数字并解析数字,其中isNaN(1,004.33) 返回 true 并引发错误。

标签: angular rxjs numbers pipe currency


【解决方案1】:

数字管道的输出可能并不总是数字。根据本地情况,它可能会以某种格式结束,它本身不能再解析为数字。

因此,如果您只是省略数字管道并直接使用货币管道解析 totalPrice$ 值,它应该可以工作。

{{totalPrice$ | async | currency: "USD"}}

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2020-05-09
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多