【问题标题】:Removing Comma from number pipe in angular2从angular2中的数字管道中删除逗号
【发布时间】:2017-12-27 13:14:16
【问题描述】:

我是 Angular 2 的初学者。我正在尝试使用 Angular 显示一些数据。这是我的代码部分:

  <span>Value :</span> <span>{{myvalue| number : '1.2-2'}}</span>

以上部分将显示值,例如:“124,500.00”。没关系,但我只需要删除逗号并将数据显示为 124500.00。这也不是货币类型。

我试过这样的东西,但它不起作用

   <span>Value :</span> <span>{{myvalue| number: '.2-3''}}</span>

我该怎么做?我可以使用任何自定义管道吗?

提前致谢

【问题讨论】:

    标签: angular angular-pipe


    【解决方案1】:

    事实上,DecimalPipe 似乎没有直接参数来更改或删除小数点。最好自己编写管道来删除小数点。

    您可以编写自己的管道来完全替换当前使用的 DecimalPipe(单个管道用于所有内容),也可以编写一个在使用 DecimalPipe 后删除逗号的管道(链式管道)。最后一个选项可能看起来像这样(我从this 答案中得到了代码,向 Adrien 致敬)。

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'noComma'
    })
    export class NoCommaPipe implements PipeTransform {
    
      transform(val: number): string {
        if (val !== undefined && val !== null) {
          // here we just remove the commas from value
          return val.toString().replace(/,/g, "");
        } else {
          return "";
        }
      }
    }
    

    之后你可以像这样链接管道。

     <span>Value :</span> <span>{{myvalue| number : '1.2-2' | noComma}}</span>
    

    记得在你的模块中声明你的管道。

    【讨论】:

    • 这只有在输入有逗号作为千位分隔符时才有效。示例:美国格式为 1,000.00,德语格式为 1.000,00。 @angular/common 具有按语言环境获取小数点分隔符的功能:getLocaleNumberSymbol()。千位分隔符为 ',' 如果小数为 '.'反之亦然。
    【解决方案2】:

    更改了 REPLACE 参数,以便删除所有逗号 (10,000,000 = 10000000),否则我最终得到 (10,000,000 = 10000,000)。根据 Benedikt,其他一切都运行良好。

    @Pipe({
        name: 'noComma'
    })
    export class NoCommaPipe implements PipeTransform {
    
     transform(val: number): string {
      if (val !== undefined && val !== null) {
        // here we just remove the commas from value
        return val.toString().replace(/,/g, "");
      } else {
        return "";
      }
     }
    }
    

    【讨论】:

    • 哇,我什至没有注意到你的答案,直到有人评论我的,但你当然完全正确,我更新了我的答案以满足需求。谢谢!
    【解决方案3】:

    在 app.module.ts 中添加这个

    import localeFr from '@angular/common/locales/fr';
    registerLocaleData(localeFr);
    

    以html组件为例(值=124566):

    {{ value | number: '':'fr-FR' }}
    

    【讨论】:

      【解决方案4】:

      角数使用decimalPipe,此解决方案适用于角2及更多

      https://angular.io/api/common/DecimalPipe

      由于它使用的是语言环境,因此您必须更改语言环境以更改管道显示它的方式

      import { registerLocaleData } from '@angular/common';
      import localeFr from '@angular/common/locales/fr';
      
      // the second parameter 'fr' is optional
      registerLocaleData(localeFr, 'fr');
      

      供参考:https://angular.io/guide/i18n#i18n-pipes

      【讨论】:

      • 这将更改整个应用程序的各种日期、数字和货币相关的内容。我不会推荐这个。
      【解决方案5】:

      为了去除小数点,我的做法是:

      {{ someNumber | number : '1.0-0' }}
      

      【讨论】:

        猜你喜欢
        • 2020-03-14
        • 2017-08-12
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 1970-01-01
        相关资源
        最近更新 更多