Search code examples
angularpipecurrency-pipe

Angular2 currency filter formats negative numbers with parenthesis


In AngularJs currency filter formats negative numbers with parenthesis. Here I am using Angular 2 currency pipe, it doesn't format the negative number into parenthesis.

It just shows plain -$18.00 but I want to show like this ($18.00). How can I achieve this.

{{ -18 | currency }}

the result i want is ($18.00) instead of -$18.00


Solution

  • If you wish, you can easily write your own custom pipe to give you that same effect.

    @Pipe({ name: 'myCurrency' })
    export class MyCurrencyPipe implements PipeTransform {
      transform(value: number): string {
        if (value < 0) {
          return `( ${value.toFixed(2)} )`;
        }
        return value.toFixed(2);
      }
    }
    

    (Don't forget to import Pipe and PipeTransform).

    Above is a crude version. A proper version should check the input value for nulls/undefined. You could also use the existing CurrencyPipe.transform and piggyback off of that logic rather than implementing your own.

    The key takeaway is to not shy away from writing your own pipes. They are simple to implement.