Skip to content

Instantly share code, notes, and snippets.

@marawannwh
Last active March 24, 2020 01:29
Show Gist options
  • Save marawannwh/44bd17c192741f4504bf482bd82f1e17 to your computer and use it in GitHub Desktop.
Save marawannwh/44bd17c192741f4504bf482bd82f1e17 to your computer and use it in GitHub Desktop.
Javascript
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function bytesToSize(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
‎‎​
‎‎​
‎‎​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment