Search code examples
angularangular-pipeangular13

Apply existing pipe in a custom pipe


I have a Precision Pipe that gives me the desired precision number... However, that pipe does not use any other number formatting, like local thousand separator etc.

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

@Pipe({ name: 'precision' })
export class PrecisionPipe implements PipeTransform {
  transform(value: number | string, precision: number): string {
    return typeof value === 'number' ? value.toFixed(precision) : value;
  }
}

Is there a way to apply the 'number' pipe in my Precision pipe, to localize it?

Knowing that

> 444444.5.toFixed(2)
'444444.50'

// I need "444 444.50"

Solution

  • A possibility is to use the consecutive pipes in HTML

    <div>{{ myNumber | precision:myPrecision | number }}</div>
    

    If not, I tried the DecimalPipe inside my PrecisionPipe:

    import { Pipe, PipeTransform } from '@angular/core';
    import { DecimalPipe } from '@angular/common';
    
    @Pipe({ name: 'precision' })
    export class PrecisionPipe implements PipeTransform {
      transform(
        value: number | string,
        precision: number,
        locale?: string | undefined,
        digitsInfo?: string | undefined,
      ): string | number | null {
    
        let pipe = new DecimalPipe(locale ?? "en");
        return isFinite(+value) ?
          pipe.transform((+value).toFixed(precision), digitsInfo, locale)
          : value;
      }
    }
    

    The only "problem" is that that last option asks you to explicitly set the current language in the pipe...