There will come a time in any application where you would want to format a given number. Like, formatting number to comma separated strings or to currency strings.
For example, you would want to format number 1000000 to 1,000,000 or number 1234567 to 1,234,567. You get what I mean.
Now to do this the right way in Angular we can create a pipe service. Using pipe as template expression we can transform our strings. A pipe would take a input value, process it and return a transformed value.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'nf',
})
export class NumberFormatterPipe implements PipeTransform {
transform(value: number | undefined): string {
if (!value) {
return '';
}
return value.toString(10).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
}
Above is a pipe which would transform our numbers. See below code sample to use this in a template.
<div class="text-primary fw-bold">
{{ 1234567 | nf }}
</div>
Be sure to add the pipe class to the declarations of your Angular module before you start using it.
Checkout the Github repo for the complete project where this pipe is being used.