5

I'd like to achieve number formatting such that if the number is round there should be no decimal placeholders .00 and otherwise use 2 and only 2 decimal places. For example:

1.23    -> 1.23
1.23456 -> 1.24
1.2     -> 1.20
1.0     -> 1
1       -> 1

According to the docs, you can only specify range of decimal places (e.g. |number:'.0-2') and not specific choice (e.g. |number:'.0,2'); am i right or is there a way?

I'm aware I could achieve the same with some *ngIf-s but would like to avoid if possible.

skink
  • 5,133
  • 6
  • 37
  • 58
crollywood
  • 523
  • 1
  • 6
  • 17

4 Answers4

4

If you want to do more than one thing on your variable, the best practise is to create two diffrent pipes and use them together. Important is order from left to right. If you want to display only two digits you can use built-in pipes like deicmalPipe:

Angular Doc Or just check that topic: Stack overflow answer

If you want to display 1 not 1.00 you can create your custom pipe where it check if that characters are 00 or sth else. If it is 00 it return number without these digits.

Faiyaz Md Abdul
  • 546
  • 5
  • 14
  • 29
Adam A
  • 157
  • 1
  • 18
  • Thats the way to go if it turns out that it is not already supported, i'll give it a bit more time to see if someone else knows a 'built-in' way. Thanks for the tip anyway! – crollywood Oct 23 '17 at 11:48
  • I have edited my post, check link to the similar topic. – Adam A Oct 23 '17 at 11:52
  • Linked link is different problem, and easy one for that matter if you take a look at the docs XD, there is no better way than custom pipe i guess – crollywood Oct 23 '17 at 12:37
  • Did you try to implement any of this pipes? – Adam A Oct 23 '17 at 13:05
0

For displaying 1 instead of 1.0 you can try this.

{{x | number:'1.0-0'}}
Ditto P S
  • 141
  • 4
  • 15
0

You could create your own DecimalPipe like this:

@Pipe({ name: 'number' })

export class MyCurrencyPipe implements PipeTransform {
constructor(
    private decimalPipe : DecimalPipe,
) {
}

transform(value: any, digitsInfo?: string, locale?: string): string | null {
    let result;
    result = this.decimalPipe.transform(value, digitsInfo, locale);

     // …do something with your result

    return result;
    }
}

If your have this your could

  • add a removeTrailingZeros? : boolean to the transform() method.

or

  • make transform() understand a digitsInfo like '1.0,2'

And don’t forget to add MyDecimalPipe to the providers of your Module to make sure your templates use MyDecimalPipe instead of angulars DecimalPipe when writing {{ foo | number:'1.0,2' }}.

DerZyklop
  • 3,672
  • 2
  • 19
  • 27
0

For reference.. It should be {{x | number:'1.0-2'}}. This displays 0, 1 or 2 decimals depending if whole number.