Ralf
Ralf

Reputation: 309

How round calculated number in Angular 2?

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

The calculation works:

 {{ ((date | amDifference : item.startdate : 'minutes' :true)/item.duration*100)  }}

But how can I round? I tryed like this:

 {{ num | ((date | amDifference : item.startdate : 'minutes' :true)/item.duration*100) : '1.2-2' }}

But this create error:

zone.js:355 Unhandled Promise rejection: Template parse errors: Parser Error: Unexpected token (, expected identifier or keyword at column 8 in [ {{ num | ((date | amDifference : item.startdate : 'minutes' :true)/item.duration*100) : '1.2-2' }}

Upvotes: 17

Views: 91569

Answers (4)

Miguel Carvalhais Matos
Miguel Carvalhais Matos

Reputation: 1143

For 1 decimal place:

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

Upvotes: 2

edkeveked
edkeveked

Reputation: 18381

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

Upvotes: 25

Velu S Gautam
Velu S Gautam

Reputation: 902

IF its CURRENCY {{value | currency:'INR':true: '1.0-0'}}

IF need NUMBER only {{value | number:'1.0-0'}}

1.0-0 means: at least one digit before decimal point, 0 digits after decimal point.

https://angular.io/api/common/DecimalPipe

Upvotes: 12

Dimanoid
Dimanoid

Reputation: 7289

You need another pipe to do this

import {Pipe} from 'angular2/core';

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

template:

{{ date | amDifference : item.startdate : 'minutes' : true | round }}

Upvotes: 20

Related Questions