Javascript: Render file size in a human readable format to two decimal places

Displaying the size of files is one thing but formatting them so they're actually understandable by humans, Another.

I've found this useful snippet by inkdeep but corrected the bit/byte units, used a different rounding function and cleaned up the if blocks.

function humanize_filesize(fs) {
if (fs >= 1073741824) { return round_number(fs / 1073741824, 2) + ' GB'; }
if (fs >= 1048576)    { return round_number(fs / 1048576, 2) + ' MB'; }
if (fs >= 1024)       { return round_number(fs / 1024, 0) + ' KB'; }
return fs + ' B';
};

This snippet uses round_numbers() which I've written in another post.

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog