Apply existing pipe in a custom pipe [duplicate]
Asked Answered
F

1

1

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"
Ferryboat answered 16/2, 2022 at 15:32 Comment(0)
F
0

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...

Ferryboat answered 16/2, 2022 at 15:52 Comment(1)
Normally you should be able to inject the DecimalPipe in the PrecisionPipe through the constructor.Breath

© 2022 - 2024 — McMap. All rights reserved.