Tom
Tom

Reputation: 8681

applying rounding and comma separated format for both positive and negative values in angular 4

I am trying to write a pipe in angular that will do the following:

  1. Divide a number by 1000
  2. If the number is < 1000 , show two decimal places
  3. If the number is >= 1000 , round up the value
  4. Should show comma separated value if the number is >= 1000
  5. The same (1-4) should apply for negative numbers as well.

I have been able to get 1-3 working. How do I achieve points 4 and 5.

So,

e.g of point 4 would be, 1200 should be 1,200.

e.g of point 5 would be , -1200 would be -1,200.

At the moment the negative number are rounding up as the they are falling in the first if condition. i.e if (number <= 999)

export class ShortNumberDivideByThousandPipe implements PipeTransform {

  transform(number: any) {

    if (number === null) {
      return;
    }
  number = parseFloat(number);

    if (isNaN(number)) {
      return;
    }


    number = (number / 1000);

    if (number <= 999) { // hundreds
      number = number.toFixed(2);
    } else if (number >= 1000) {  // thousands
      number = number.toFixed(0);
    } return number;
  }
}

Upvotes: 0

Views: 462

Answers (1)

Gourishankar
Gourishankar

Reputation: 956

Looking at your problem it seems like you just need to divide the number by 1000 rest all formatting related things can be done by angular built in DecimalPipe. Details at :- https://angular.io/api/common/DecimalPipe , https://angular.io/api/common/formatNumber

Upvotes: 0

Related Questions