Search code examples
angularangular2-pipe

angular extended currency pipe in is not formatting string/int if there is no decimal point in input


Angular currency pipe is not converting string/int to currency format if the number is in string format and there is no decimal points in the string.

suppose the amount is 12 and I want to show $12.00, if "12" is passed, its not showing but if 12.00 is passed its working properly.

//Code

import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;

@Pipe({name: 'myCurrency'})
export class MyCurrencyPipe implements PipeTransform  {
  constructor (private _currencyPipe: CurrencyPipe) {}

  transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
    if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
      return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
    } else {
      return value;
    }
  }
}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div>{{priceNoDecimal}}</div> {{priceNoDecimal | myCurrency}}
      <div>{{priceWithDecimal}}</div> {{priceWithDecimal | myCurrency}}      
    </div>
  `,
})
export class App {
  name:string;
  priceWithDecimal: string;
  priceNoDecimal: string;
  constructor() {
    this.name = 'Angular2',
    this.priceNoDecimal = "12"
    this.priceWithDecimal = "12.00"
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyCurrencyPipe],
  providers: [CurrencyPipe],
  bootstrap: [ App ]
})
export class AppModule {}


//output

Hello Angular2

12
12
12.00
USD12.00

Plunker


Solution

  • If you look at the regexp that you have applied: /^(\d+)?\.((\d+)(-(\d+))?)?$/ it requires a decimal point.

    The following regex makes the decimal point optional /^(\d+)?\.?((\d+)(-(\d+))?)?$/