Skip to content

Instantly share code, notes, and snippets.

@KCreate
Created May 17, 2018 13:48
Show Gist options
  • Save KCreate/ff8eee17ebc6f08ed0bf03671d58e4ce to your computer and use it in GitHub Desktop.
Save KCreate/ff8eee17ebc6f08ed0bf03671d58e4ce to your computer and use it in GitHub Desktop.
Convert an amount of bytes to a human readable file size.
const bytesInKilobyte = 1000
const bytesInMegabyte = 1000000
const bytesInGigabyte = 1000000000
const bytesInTerabyte = 1000000000000
function toHumanReadable(bytes) {
if (bytes >= bytesInTerabyte) return Math.round(bytes / bytesInTerabyte * 100) / 100 + " tb";
if (bytes >= bytesInGigabyte) return Math.round(bytes / bytesInGigabyte * 100) / 100 + " gb";
if (bytes >= bytesInMegabyte) return Math.round(bytes / bytesInMegabyte * 100) / 100 + " mb";
if (bytes >= bytesInKilobyte) return Math.round(bytes / bytesInKilobyte * 100) / 100 + " kb";
return bytes + " bytes";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment