Skip to content
Advertisement

How to use the angular decimal pipe in typscript

I’m using the angular decimal pipe like this:

// Typescript
@Component({...})
export class ConfusionMatrixComponent {

    @Input()
    roundRules = '1.0-2';
}

// HTML:
<div class="value">{{ getIntensityNumber(i) | number: roundRules }}</div>

How can I use the same pipe but on a typescript function?

Advertisement

Answer

I found in a similar question how to use it: just need to import DecimalPipe from @angular/commun and use it as a service:

// Typescript
import { DecimalPipe } from '@angular/common';

@Component({...})
export class ConfusionMatrixComponent {

    @Input()
    roundRules = '1.0-2';

    constructor(private decimalPipe: DecimalPipe) { }

    getRoundNumber(num: number): string | null {
        return this.decimalPipe.transform(num, this.roundRules) ?? '0';
    }

}

// HTML:
<div class="value">{{ getRoundNumber(23.50873) }}</div>

Also, make sure you add the DecimalPipe to your providers angular module:

import { CommonModule, DecimalPipe } from '@angular/common';
@NgModule({
    declarations: [...],
    imports: [CommonModule],
    exports: [...],
    providers: [DecimalPipe]
})
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement