number.js 779 B

123456789101112131415161718
  1. export function formatBytes(bytes, options) {
  2. options = Object.assign({
  3. unit: 'bytes',
  4. locale: undefined
  5. }, options);
  6. const byteUnits = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  7. const bitUnits = ['b', 'kbit', 'Mbit', 'Gbit', 'Tbit', 'Pbit', 'Ebit', 'Zbit', 'Ybit'];
  8. const units = options.unit === 'bytes' ? byteUnits : bitUnits;
  9. const isNegative = bytes < 0;
  10. bytes = Math.abs(bytes);
  11. if (bytes === 0)
  12. return '0 B';
  13. const i = Math.min(Math.floor(Math.log10(bytes) / 3), units.length - 1);
  14. const num = Number((bytes / Math.pow(1000, i)).toPrecision(3));
  15. const numString = num.toLocaleString(options.locale);
  16. const prefix = isNegative ? '-' : '';
  17. return `${prefix}${numString} ${units[i]}`;
  18. }