Removing Comma from number pipe in angular2

Jithin j picture Jithin j · Dec 27, 2017 · Viewed 15.2k times · Source

I am a beginner in Angular 2.I'm trying to display some data using angular. this is my code part:

  <span>Value :</span> <span>{{myvalue| number : '1.2-2'}}</span>

Above part will display Value as for eg: "124,500.00". Its ok but i need to remove comma and display data as 124500.00 only. Also this is not a currency type.

I tried some thing like this and its not working

   <span>Value :</span> <span>{{myvalue| number: '.2-3''}}</span>

How can i do that?Can i use any custom pipe?

Thanks in advance

Answer

Benedikt Schmidt picture Benedikt Schmidt · Dec 27, 2017

In fact it looks like there's no direct parameter to the DecimalPipe to change or remove the decimal points. It would probably be the best to write your own pipe to remove the decimal points.

You can either write your own pipe that fully replaces the current use of the DecimalPipe (single pipe for everything) or you write a pipe that removes the commas after the DecimalPipe was used (chained pipes). The last option could look something like this (I got the code from this answer, so greetings to Adrien).

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

@Pipe({
  name: 'noComma'
})
export class NoCommaPipe implements PipeTransform {

  transform(val: number): string {
    if (val !== undefined && val !== null) {
      // here we just remove the commas from value
      return val.toString().replace(/,/g, "");
    } else {
      return "";
    }
  }
}

You can chain the pipes afterwards like this.

 <span>Value :</span> <span>{{myvalue| number : '1.2-2' | noComma}}</span>

Just remember to declare your pipe in your module.