Skip to content

Instantly share code, notes, and snippets.

@MWers
Created September 5, 2013 06:17
Show Gist options
  • Save MWers/6446640 to your computer and use it in GitHub Desktop.
Save MWers/6446640 to your computer and use it in GitHub Desktop.
Convert bytes to human readable format, based on code here: http://codeaid.net/javascript/convert-size-in-bytes-to-human-readable-format-(javascript)
bytesToSize = function (bytes, precision) {
var kilobyte = 1024;
var megabyte = kilobyte * 1024;
var gigabyte = megabyte * 1024;
var terabyte = gigabyte * 1024;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + ' B';
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte).toFixed(precision) + ' KB';
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte).toFixed(precision) + ' MB';
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte).toFixed(precision) + ' GB';
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + ' TB';
} else {
return bytes + ' B';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment