【问题标题】:AngularJS .00 currency filterAngularJS .00 货币过滤器
【发布时间】:2014-09-05 09:59:54
【问题描述】:

我使用 .00 货币过滤器来自:AngularJS currency filter: can I remove the .00 if there are no cents in the amount?

但是,如何调整过滤器以按逗号分割值?

例如,

而不是 456789 英镑 它应该显示:456,789 英镑

这是我制作的一个 plunker:http://plnkr.co/edit/uDFWkPAmc7PrgDwHPDho?p=preview

过滤器:

app.filter('myCurrency', ['$filter', function ($filter) {


return function(input) {
    input = parseFloat(input);
    if(input % 1 === 0) {
      input = input.toFixed(0);
    }
    return '£' + input;
  };
}]);

【问题讨论】:

    标签: angularjs angularjs-scope angular-filters


    【解决方案1】:

    由于您可以链接过滤器,因此您可以使用 _.str 修剪过滤器之类的东西:

    jsFiddle

    <p>My value with currency trimming filter: {{ myValue | currency:'&pound;' | _.str: 'trim':['.00'] }}</p>
    

    结果:

    // My value with currency trimming filter: £242,737
    

    如果您计划支持不同国家/地区表示的货币,并且由于货币的 l18n 功能而使用逗号“,”而不是点,您可以考虑包含两者的最终版本:

    <p>My value with currency trimming filter: {{ myValue | currency:'&pound;' | _.str: 'trim':['.00'] | _.str: 'trim':[',00'] }}</p>
    

    【讨论】:

      【解决方案2】:

      这是一种方法:

      app.filter('myCurrency', ['$filter', function ($filter) {
        return function(input) {
          input = parseFloat(input);
          if(input % 1 === 0) {
            input = input.toFixed(0);
          }
      
          return '£' + (''+input).replace(/(\d)(?=(\d{3})+($|\.))/g, "$1,");
        };
      }]);
      

      Plunker

      编辑

      更新了过滤器以使用正则表达式。

      【讨论】:

      • 谢谢,但是看看当您将 myValue 更改为 10000 时会发生什么...过滤结果为 £10,0
      • 这绕过了 Angular 货币过滤器的 i18n 功能。以及相当复杂的解决方案。
      • @Plantface,我帖子的第一行:“这是一种方法”。当然还有很多其他方法可以做到这一点......这是一种:)
      猜你喜欢
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多