1

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

Sadid Khan
  • 1,836
  • 20
  • 35

2 Answers2

1

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.

snorkpete
  • 14,278
  • 3
  • 40
  • 57
0

Here it is my custom pipe implemantation:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'accounting'
})
export class AccountingPipe implements PipeTransform {

  transform(value: number, ...args: unknown[]): string {
    if(value==null || value == undefined) return "-";
    let data = "$" + value.toLocaleString('en');
    if ( data.indexOf(".") < 0 ) { // to make sure there is always two decimals
      data = data + ".00";
    }
    if (value < 0) { // adding the desired parenthesis and removing the '-' sign
      data = "(" + data + ")";
      data = data.replace("-","");
    }
    return data;
  }

}
Pepe Alvarez
  • 1,218
  • 1
  • 9
  • 15