UNPKG

1.21 kBJavaScriptView Raw
1var enforcePrecision = require('./enforcePrecision');
2 var _defaultDict = {
3 thousand: "K",
4 million: "M",
5 billion: "B",
6 };
7
8 /**
9 * Abbreviate number if bigger than 1000. (eg: 2.5K, 17.5M, 3.4B, ...)
10 */
11 function abbreviateNumber(val, nDecimals, dict) {
12 nDecimals = nDecimals != null ? nDecimals : 1;
13 dict = dict || _defaultDict;
14 val = enforcePrecision(val, nDecimals);
15
16 var str, mod;
17 var negative = false;
18
19 if (val < 0) {
20 val = -val;
21 negative = true;
22 }
23
24 if (val < 1000000) {
25 mod = enforcePrecision(val / 1000, nDecimals);
26 // might overflow to next scale during rounding
27 str = mod < 1000 ? mod + dict.thousand : 1 + dict.million;
28 } else if (val < 1000000000) {
29 mod = enforcePrecision(val / 1000000, nDecimals);
30 str = mod < 1000 ? mod + dict.million : 1 + dict.billion;
31 } else {
32 str = enforcePrecision(val / 1000000000, nDecimals) + dict.billion;
33 }
34
35 if (negative) {
36 str = "-" + str;
37 }
38
39 return str;
40 }
41
42 module.exports = abbreviateNumber;
43