最终效果
242 => 242
369511 => 369,511
41262132 => 41,262,132
6456122331 => 6,456,122,331
ng g p shared/pipe/number-format
...
import { NumberFormatPipe } from './pipe/number-format.pipe';
@NgModule({
declarations: [NumberFormatPipe],
...
exports: [
...
NumberFormatPipe
],
...
})
// number-format.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberFormat'
})
export class NumberFormatPipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
return this.toThousands(value);
}
toThousands(num) {
var num = (num || 0).toString(), result = '';
while (num.length > 3) {
result = ',' + num.slice(-3) + result;
num = num.slice(0, num.length - 3);
}
if (num) { result = num + result; }
return result;
}
}
import { SharedModule } from '@app/shared';
@NgModule({
...
imports: [
SharedModule,
...
]
})
<div class="num">{{ '12332132132' | numberFormat }}</div>
测试数字是否被转换为千分位格式。至此,一个简单的 Angular 数字格式化管道就完成了。