如何在Angular 4中为数字管道指定千位分隔符

dra*_*fly 30 angular

如何为Angular 4中的数字管道指定/覆盖默认(区域设置)千位分隔符,例如?

{{p.total | number}}
Run Code Online (Sandbox Code Playgroud)

Adr*_*lat 20

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

如果您不想更改整个项目的区域设置或关联的默认值,我认为您最好的方法是编写自己的管道来处理您的特殊情况.不用担心,管道非常容易编写.

{{p.total | number:'':'fr-FR'}}
Run Code Online (Sandbox Code Playgroud)

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

  • @PardeepJain,好吧,您将在 `transform` 方法中编写与您要查找的格式相对应的逻辑。但我认为有关这种实现的细节超出了这个 SO 线程的范围。 (2认同)

Ita*_*mar 14

数量:1234567

使用以下管道:

{{element.total | 2号'}}

为了生产1,234,567.00

并使用以下管道:

{{element.total | 2号.'}}

为了摆脱额外的0并产生1,234,567

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

注意'2' 表示小数后的整数.

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

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

  • 这是关于小数分隔符的回答,但问题是关于**千**分隔符. (7认同)
  • 使用“数字”管道时,您将获得千位分隔符 (2认同)

Jan*_*ana 7

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

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));
  }

}
Run Code Online (Sandbox Code Playgroud)

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

<span class="strong">{{Price  | amountConverter:locale}}</span>
Run Code Online (Sandbox Code Playgroud)

数字格式将根据区域设置的值更改.

有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat.


Jav*_*tes 6

您可以使用与使用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 );
  }

}
Run Code Online (Sandbox Code Playgroud)

card-component.html

<!-- result: 1.234.567,987 -->
<span>{{ value | number:'':'es' }}</span>
Run Code Online (Sandbox Code Playgroud)

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