Create a simple number formatter pipe in Angular.

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.

Published by Kumar Gandhi K

Hi! I’m Kumar and I live in Bangalore (IN) with my family. By profession I’m a Web Developer experienced in a vast variety of frameworks and technologies, like, HTML, CSS, JavaScript, Angular, Bootstrap… Using these i have built or sometimes maintained mid market and enterprise level applications. I worked for few software companies over the years and on few domains like finance, field-service and storage. I also did consulting job at one point. I am loyal and hard (or for better word smart) working individual. In my free time I read books, in fact I buy a lot of books hoping that some day I might find all the time in the world to read them and I also enjoy watching TV.

Leave a comment