如何为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中以使用它.
Ita*_*mar 14
数量:1234567
使用以下管道:
{{element.total | 2号'}}
为了生产1,234,567.00
并使用以下管道:
{{element.total | 2号.'}}
为了摆脱额外的0并产生1,234,567
-------------------------------------------------- --------------------------------------
注意'2' 表示小数后的整数.
例如,当使用此管道在表中加载值0时,显示的值将为"00"(因为"2")
要解决这个问题,请使用'1.' 而是当输入值为0时.
以下是我的解决方案,它将对某人有所帮助.
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.
您可以使用与使用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/DecimalPipe和https://angular.io/guide/i18n#setting-up-the-locale-of-your-app官方文档中查看其他可能性.
归档时间: |
|
查看次数: |
47217 次 |
最近记录: |