wikiti
10/11/2016 - 10:04 AM

Human byte size

Human byte size

var toHumanSize = function(bytes) {
  var list = ['B', 'kB', 'MB', 'GB', 'TB']; // Add more units, if you need to.
  var factor = 1.0 / 1000.0;                // You can use 1024 for bits instead!
  var unit = list.shift();

  while(list.length > 0 && bytes * factor >= 1) {
    bytes = bytes * factor;
    unit = list.shift();
  }

  return { value: bytes, unit: unit };
}

var toHumanSizeString = function(bytes, decimals) {
  if(decimals === undefined)
    decimals = 2;

  var data = toHumanSize(bytes);
  return data.value.toFixed(decimals) + ' ' + data.unit;
}

// Examples
console.log(toHumanSize(3024)); // { value: 3.024, unit: 'kB' }
console.log(toHumanSizeString(3024)); // "3.024 kB"