0

I am building an angular app involving large amounts. I'd like to shorten the way their are displayed so I built a quick and dirty filter replacing '1000000000' by '$1.0Bn' for example but it is really dirty and it just truncate the numbers instead of rounding them up.

Here it is:

  .filter('largeAmountCurrency', function() {
    return function(input) {
      if (!input) return;

      var oneBillion = 1000000000,
          oneMillion = 1000000;

      if (input > oneBillion) 
        return '$' + parseInt(input / oneBillion) + '.' + 
                String(parseInt(input - parseInt(input/oneBillion))).substring(1,3) + 'Bn';

      if (input > oneMillion) 
        return '$' + parseInt(input / oneMillion) + '.' + 
                String(parseInt(input - parseInt(input/oneMillion))).substring(1,3) + 'M';

      return input;
    }
  });

Is their any prebuilt filter in angular which does this job? Or how can I shorten it dramatically?

Spearfisher
  • 8,445
  • 19
  • 70
  • 124

1 Answers1

2

You can compute a few things using Mathematical logarithm log!. This will help you knowing the number of digits your input has.

Example (log is base 10 logarithm, ln is napierian logarithm) :

log(12345678910) = ln(12345678910)/ln(10) = 10

Here, 10 is the number of digits after the first '1'.

Based on this information you can compute a simplified value, and then round it with toFixed! (This works with IE5.5+, Javascript 1.5, I assumed you get it when you use AngularJS)

A complete example below :

var number = 12345678910;

var digits = 2;
var suffix = ["", "K.", "M.", "B."];

var nbDigits = Math.round(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;

var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);

var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];
yunandtidus
  • 3,847
  • 3
  • 29
  • 42
  • I want number to be displayed as 1k if it is 1000. Could you please tell me the logic – Kartheek Sarabu Feb 21 '19 at 10:35
  • 1
    Please notice that I changed `parseInt` to `Math.round`, now you got : `$ 1.00 K.` You can obtain the expected behavior by changing `digits` to 0 and `suffix` to `["", "k", "m", "b"]` – yunandtidus Feb 25 '19 at 10:01