0

In angular2, we can used pipes to format numbers. For example:

{{selectedTeam.teamSalary | currency: 'USD':true}}

This gives us something like $152,524,668.00

The Angular2 Pipes documentation doens't cover a whole lot of specifics so my question is, is there a way to (using angular2 pipes) to convert a number like $152,524,668.00 to $152.5m?

This question gives me code to do it, but looking for a more 'Anulgar2-specific' way to do it (if one exists).

Convert long number into abbreviated string in JavaScript, with a special shortness requirement

Community
  • 1
  • 1
mwilson
  • 12,295
  • 7
  • 55
  • 95
  • 2
    Write your own pipe. https://angular.io/docs/ts/latest/guide/pipes.html#!#custom-pipes – fubar Mar 28 '17 at 03:08
  • Yea, I saw I that as an option, just want to see if there is any support within the available pipes/pipe options first. – mwilson Mar 28 '17 at 03:09

1 Answers1

1

There isn't a built in pipe to do what you want, but as @Rob suggested, you can write your own pipe pretty easily.

A pipe is just a class containing a transform method that takes an input and converts it to some other value. The question you referred to already outlines the logic you'd need to do the conversion, so honestly, the 'angular way' is just to wrap that logic in a pipe.

 @Pipe({ name: 'myMoney' })
 export class MyMoneyPipe implements PipeTransform {

   transform(value: number): string {
    var newValue = value;
    if (value >= 1000) {
        var suffixes = ["", "k", "m", "b","t"];
        var suffixNum = Math.floor( (""+value).length/3 );
        var shortValue = '';
        for (var precision = 2; precision >= 1; precision--) {
            shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
            var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
            if (dotLessShortValue.length <= 2) { break; }
        }
        if (shortValue % 1 != 0)  shortNum = shortValue.toFixed(1);
        newValue = shortValue+suffixes[suffixNum];
    }
    return newValue;
   }
 }
snorkpete
  • 14,278
  • 3
  • 40
  • 57