abbreviate.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. var enforcePrecision = require('./enforcePrecision');
  2. var _defaultDict = {
  3. thousand : 'K',
  4. million : 'M',
  5. billion : 'B'
  6. };
  7. /**
  8. * Abbreviate number if bigger than 1000. (eg: 2.5K, 17.5M, 3.4B, ...)
  9. */
  10. function abbreviateNumber(val, nDecimals, dict){
  11. nDecimals = nDecimals != null? nDecimals : 1;
  12. dict = dict || _defaultDict;
  13. val = enforcePrecision(val, nDecimals);
  14. var str, mod;
  15. if (val < 1000000) {
  16. mod = enforcePrecision(val / 1000, nDecimals);
  17. // might overflow to next scale during rounding
  18. str = mod < 1000? mod + dict.thousand : 1 + dict.million;
  19. } else if (val < 1000000000) {
  20. mod = enforcePrecision(val / 1000000, nDecimals);
  21. str = mod < 1000? mod + dict.million : 1 + dict.billion;
  22. } else {
  23. str = enforcePrecision(val / 1000000000, nDecimals) + dict.billion;
  24. }
  25. return str;
  26. }
  27. module.exports = abbreviateNumber;