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

0 Comments

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.

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

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