【问题标题】:How to specify locale thousand separator for number pipe in Angular 4如何在Angular 4中为数字管道指定语言环境千位分隔符
【发布时间】:2017-11-24 03:05:55
【问题描述】:

如何在 Angular 4 中为数字管道指定/覆盖默认(语言环境)千位分隔符,例如?

{{p.total | number}}

?

【问题讨论】:

标签: angular


【解决方案1】:

以下是我的解决方案,它将对某人有所帮助。

   
import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'amountConverter'
    })
    export class AmountConverterPipe implements PipeTransform {
    
      transform(value: number | string, locale?: string): string {
        return new Intl.NumberFormat(locale, {
          minimumFractionDigits: 2
        }).format(Number(value));
      }
    
    }

可以通过更改 minimumFractionDigits 的值来更改位数。 在html中可以如下使用

<span class="strong">{{Price  | amountConverter:locale}}</span>

数字格式会根据语言环境的值而改变。

详情请咨询https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

【讨论】:

    【解决方案2】:

    我为了我的目的实现了这个。 例如:- 12345.67 => 12,345.67

    首先,我使用 ng g pipe pipes/thousandSeparator 生成了一个 PIpe,然后我像这样编辑了该文件

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'thousandSeparator'
    })
    export class ThousandSeparatorPipe implements PipeTransform {
    
      transform(nStr: any): any {
        if (nStr === '') { return ''; }
        let x, x1, x2, rgx;
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x[1];
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
          x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + (x2 ? `.${x2}` : '');
      }
    }
    

    我也将它添加到 app.module.ts 中的提供程序中

    providers: [ThousandSeparatorPipe]
    

    那么,我可以这样使用它。

    在组件中

    import { Component, OnInit } from '@angular/core';
    import { ThousandSeparatorPipe } from 'src/app/pipes/thousand-separator.pipe';
    
    @Component({
      selector: 'app-my',
      templateUrl: './my.component.html',
      styleUrls: ['./my.component.scss']
    })
    export class MyComponent implements OnInit {
    
      value = 12345.67;
    
      constructor(private thousandSeparator: ThousandSeparatorPipe) { }
    
      ngOnInit() {
        console.log(this.thousandSeparator.transform(this.value));
      }
    
    }
    

    在html中

    <p>{{value | thousandSeparator}}</p>
    

    【讨论】:

      【解决方案3】:

      您可以为此编写自定义管道。

      import { Pipe, PipeTransform }     from '@angular/core';
      
      @Pipe({name: 'seprator'})
      export class Seprator implements PipeTransform {
        
        constructor() {
      
        }
      
        transform(value: string, unit: string): string {
      
          if(value == undefined)
          {
              return '';
          }
          let n = parseInt(value);
      
          const rx =  /(\d+)(\d{3})/;
          return String(n).replace(/^\d+/, function (w) {
              var res = w;
              while (rx.test(res)) {
                  res = res.replace(rx, '$1٬$2');
              }
              return res;
          });
      
        }
      }

      【讨论】:

        【解决方案4】:

        角度 5+

        从 Angular 5 开始,在十进制管道中添加了一个语言环境参数,您可以在官方文档中看到:https://angular.io/api/common/DecimalPipe。这意味着您可以在调用管道时直接选择您的语言环境,例如:

        {{p.total | number:'':'fr-FR'}}
        

        请注意,这也会改变小数点分隔符。


        角度 2+

        或者如果您只想更改千位分隔符...

        根据 Angular 关于 DecimalPipe 的文档:https://v2.angular.io/docs/ts/latest/api/common/index/DecimalPipe-pipe.html,没有明确的参数可以添加到管道调用中以异常更改用于格式化的字符。

        如果您不想更改整个项目的语言环境或关联的默认值,我认为您最好的办法是编写自己的管道来处理您的特殊情况。别担心,管道非常容易编写。

        import { Pipe, PipeTransform } from '@angular/core';
        
        @Pipe({
          name: 'numberfr'
        })
        export class FrenchDecimalPipe implements PipeTransform {
        
          transform(val: number): string {
            // Format the output to display any way you want here.
            // For instance:
            if (val !== undefined && val !== null) {
              return val.toLocaleString(/*arguments you need*/);
            } else {
              return '';
            }
          }
        }
        

        不要忘记将其添加到 NgModule 中以使用它。

        【讨论】:

        • toLocaleString 因大数字而失败。例如大于 9007199254740991。超过这个值是不安全的 JS 数值。
        • @Shantanu,哇,刚刚了解了这个 JS 限制,谢谢!看起来你需要担心的不仅仅是格式化功能,但如果你超越了MAX_SAFE_INTEGER。有什么建议可以改进我的答案吗?
        • 如果我需要获得类似1,23,455,667 的价值怎么办?
        • @PardeepJain,您可以编写与您在transform 方法中查找的格式相对应的逻辑。但我认为关于这种实现的细节超出了这个 SO 线程的范围。
        • @AdrienBrunelat 是的,但是认为您可能会实施相同的管道,所以在这里问,无论如何谢谢
        【解决方案5】:

        我知道这可能会迟到,但希望对您有所帮助。角度2及以上

        import { DecimalPipe } from '@angular/common';
        import { Component, OnInit } from '@angular/core';
        
        @Component( {
          selector: 'app-card',
          templateUrl: './card.component.html',
          styleUrls: [ './card.component.css' ]
        } )
        export class CardComponent implements OnInit {
        
         value = 1234567.987;
        
         constructor(private decimalPipe: DecimalPipe) { }
        
         ngOnInit() {
           //here is how to get it
           let newValue = this.decPipe.transform(this.value, '.2');
           //you can now use the newValue
           }
        
         }
        

        如果你想在 html 中这样做,只需:

        {{ value | number: '.2'}}
        

        【讨论】:

          【解决方案6】:

          号码:1234567

          使用以下管道:

          {{ 元素.总数 |编号:'.2'}}

          为了产生1,234,567.00

          并使用以下管道:

          {{ 元素.总数 |编号:'2.'}}

          为了去掉多余的 0 并产生 1,234,567

          ------------------------------------------ --------------------------------------------

          注意“2.”表示小数点后的整数个数。

          例如,当使用此管道将值 0 加载到表中时,显示的值将是 '00'(因为 '2')

          要解决这个问题,请使用“1”。而是当输入值为 0 时。

          【讨论】:

          • 这是关于小数点分隔符的回答,但问题是关于 thousands 分隔符的。
          • 当使用“数字”管道时,你会得到千位分隔符
          • 但问题是“如何指定/覆盖默认(语言环境)千位分隔符”。这个答案是否告诉提问者如何指定分隔符?或者如何覆盖它?我没看到。
          • 在使用数字管道时,您会得到千位分隔符,当不使用它时,没有分隔符。至于指定或覆盖,没有办法,因为这将允许您更改人类分隔数千而不是数十或数百的方式,这在引用数字而不是字符串时是不可接受的,如果它是一个字符串,那将是一个不同的案例。
          【解决方案7】:

          您可以使用 locale,就像在此示例中使用 Angular 6.0.2 进行测试一样:

          card-component.ts

          import { registerLocaleData } from '@angular/common';
          import es from '@angular/common/locales/es';
          import { Component, OnInit } from '@angular/core';
          
          @Component( {
            selector: 'app-card',
            templateUrl: './card.component.html',
            styleUrls: [ './card.component.css' ]
          } )
          export class CardComponent implements OnInit {
          
            value = 1234567.987;
          
            constructor() { }
          
            ngOnInit() {
              registerLocaleData( es );
            }
          
          }
          

          card-component.html

          <!-- result: 1.234.567,987 -->
          <span>{{ value | number:'':'es' }}</span>
          

          您可以在https://angular.io/api/common/DecimalPipehttps://angular.io/guide/i18n#setting-up-the-locale-of-your-app 官方文档中查看其他可能性。

          【讨论】:

            猜你喜欢
            • 2023-04-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-06-11
            • 2016-02-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多