index.js 635 B

123456789101112131415161718192021222324252627
  1. 'use strict';
  2. var numberIsNan = require('number-is-nan');
  3. module.exports = function (num) {
  4. if (typeof num !== 'number' || numberIsNan(num)) {
  5. throw new TypeError('Expected a number, got ' + typeof num);
  6. }
  7. var exponent;
  8. var unit;
  9. var neg = num < 0;
  10. var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  11. if (neg) {
  12. num = -num;
  13. }
  14. if (num < 1) {
  15. return (neg ? '-' : '') + num + ' B';
  16. }
  17. exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1);
  18. num = Number((num / Math.pow(1000, exponent)).toFixed(2));
  19. unit = units[exponent];
  20. return (neg ? '-' : '') + num + ' ' + unit;
  21. };