Currency Filter For Large Amount In Angular
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 exa
Solution 1:
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];
Post a Comment for "Currency Filter For Large Amount In Angular"