DEV Community

Cover image for Custom pipe to format numbers in Angular
MD ASHRAF
MD ASHRAF

Posted on

Custom pipe to format numbers in Angular

Here we are creating custom pipe to format large numbers (e.g., 1,000,000 → 1M).

pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'largeNumberFormat'
})
export class LargeNumberFormatPipe implements PipeTransform {
  transform(value: number): string {
    if (value >= 1000000) { // dividing number by 10L since 1M == 10L
      return (value / 1000000).toFixed(1) + 'M'; // toFixed(1) rounding till one decimal value
    } else if (value >= 1000) {
      return (value / 1000).toFixed(1) + 'K';
    } else {
      return value.toString(); // returning number itself in string format if less than thousand.
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Usage in component.html

<p>{{ 1000000 | largeNumberFormat }}</p> // Output: 1.0M
<p>{{ 1000 | largeNumberFormat }}</p> // Output: 1.0K
<p>{{ 500 | largeNumberFormat }}</p> // Output: 500
Enter fullscreen mode Exit fullscreen mode

Important: By default pipe is pure, meaning they only execute when the input value changes. If you want the pipe to execute on every change detection cycle, you can make it impure by setting the pure property to false:


@Pipe({
  name: 'largeNumberFormat',
  pure: false
})
Enter fullscreen mode Exit fullscreen mode

When is an impure pipe useful?

An impure pipe is useful when the pipe's output depends on something other than the input value, such as:

  • Current time: If you want to display the time elapsed since a certain date, you would need an impure pipe to update the output every second.

  • Random numbers: If you want to generate a random number based on the input value, an impure pipe would be necessary.

  • External data: If the pipe's output depends on external data that can change outside of the component's control, an impure pipe might be necessary.

However, keep in mind that **impure pipes can have performance implications**, as they are executed on every change detection cycle. Therefore, use them judiciously and only when necessary.

📌📌 More Angular interview related stuff here:
Rxjs and Angular bonding

Top comments (0)