Skip to content

Instantly share code, notes, and snippets.

@wikiti
Last active June 19, 2017 10:48
Show Gist options
  • Save wikiti/4eaedeef985b83fb33a74f76d7b6877a to your computer and use it in GitHub Desktop.
Save wikiti/4eaedeef985b83fb33a74f76d7b6877a to your computer and use it in GitHub Desktop.
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment