Angular 2 - how round calculated number?

后端 未结 3 1874
一个人的身影
一个人的身影 2021-01-12 05:37

I have a *ngFor loop and want to calculate a value - with 2 decimal places.

The calculation works:

3条回答
  •  不知归路
    2021-01-12 06:20

    One can use angular built-in pipe such as number

    {{value | number:'1.0-0'}}

    If one wants to have an implementation of it:

    @Pipe({name: 'round'})
    export class RoundPipe {
      transform (input:number) {
        return Math.floor(input);
      }
    }
    

    Use in the template

    {{1,1 | round}} => 1
    {{2,1 | round}} => 2
    

    Another useful pipe is a round ten :

    @Pipe({name: 'roundTen'})
    export class RoundTenPipe implements PipeTransform {
      transform(value: number): number {
        return Math.round(value / 10) * 10;
      }
    }
    

    Use in the template

    {{11 | roundTen}} => 10
    {{21 | roundTen}} => 20
    

提交回复
热议问题