Skip to content

Instantly share code, notes, and snippets.

@diogoalexsmachado
Created May 7, 2021 11:35
Show Gist options
  • Save diogoalexsmachado/3b92e36671ecf5434a934137b03689b8 to your computer and use it in GitHub Desktop.
Save diogoalexsmachado/3b92e36671ecf5434a934137b03689b8 to your computer and use it in GitHub Desktop.
formatBytes.js
function formatBytes(bytes) {
var marker = 1024; // Change to 1000 if required
var decimal = 3; // Change as required
var kiloBytes = marker; // One Kilobyte is 1024 bytes
var megaBytes = marker * marker; // One MB is 1024 KB
var gigaBytes = marker * marker * marker; // One GB is 1024 MB
var teraBytes = marker * marker * marker * marker; // One TB is 1024 GB
// return bytes if less than a KB
if(bytes < kiloBytes) return bytes + " Bytes";
// return KB if less than a MB
else if(bytes < megaBytes) return(bytes / kiloBytes).toFixed(decimal) + " KB";
// return MB if less than a GB
else if(bytes < gigaBytes) return(bytes / megaBytes).toFixed(decimal) + " MB";
// return GB if less than a TB
else return(bytes / gigaBytes).toFixed(decimal) + " GB";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment