Display number in Million or Thousand format in angular 4

Tom picture Tom · Feb 2, 2018 · Viewed 14.9k times · Source

I am trying to display number format in my angular 4 application. Basically what i am looking at is if the number is in 12.23 millions then it should display For e.g 12.2M (One decimal place)

If the number is 50,000.123 then 50.1K

How do i achieve that in angular. Do I need to write a directive ? Are there any inbuilt pipes in angular ?

structure

export interface NpvResults  {

            captiveInsYear: number[];
            captiveInsPremiumPaid: number[];
            captiveInsTaxDeduction: number[];
            captiveInsLoanToParent: number[];
            captiveInsCapitalContribution: number[];
            captiveDividentDistribution: number[];
            captiveInsTerminalValue: number[];

        }

The array is initialized to the following value

this.sourceResults.captiveInsPremiumPaid = [1,2,3,4,5];

The html

<td *ngFor= "let item of NpvResults.captiveInsPremiumPaid" >{{item}}</td>

Answer

mQuiroz picture mQuiroz · Jun 18, 2018

you can create PIPE

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

@Pipe({
  name: 'thousandSuff'
})
export class ThousandSuffixesPipe implements PipeTransform {

  transform(input: any, args?: any): any {
    var exp, rounded,
      suffixes = ['k', 'M', 'G', 'T', 'P', 'E'];

    if (Number.isNaN(input)) {
      return null;
    }

    if (input < 1000) {
      return input;
    }

    exp = Math.floor(Math.log(input) / Math.log(1000));

    return (input / Math.pow(1000, exp)).toFixed(args) + suffixes[exp - 1];


  }

}

implement in the view

{{ model | thousandSuff  }} <!-- 0 decimals -->

{{ model | thousandSuff : 2  }}  <!-- X decimals -->

result

{{ 22600000 | thousandSuff }} -> 23M

{{ 22600000 | thousandSuff : 2 }} -> 22.60M