“size” is in bytes, the rest you should be able to figure out.
function readableFileSize(size) {
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = 0;
while(size >= 1024) {
size /= 1024;
++i;
}
return size.toFixed(1) + ' ' + units[i];
}
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = 0;
while(size >= 1024) {
size /= 1024;
++i;
}
return size.toFixed(1) + ' ' + units[i];
}
4 thoughts on “Human-readable file size in JavaScript”
function fileSize(size) {
var i = Math.floor( Math.log(size) / Math.log(1024) );
return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ‘ ‘
+ [‘B’, ‘kB’, ‘MB’, ‘GB’, ‘TB’][i];
}
Sergei
Thanks Sergei. That should work well too, although I don’t know why you have the *1 on there.
Mark
*1 allows to show values such as 5.00 as 5, but keeps the decimals if there are any
Michael
Thank you! This is a beautiful function!
Amanda Patricia Koster