Recently, I needed to figure out a way to convert the size of a file, which is being returned in bytes, to a string representation.  So, given a file size in bytes like 349792 the string “342KB" would be returned.  Inspired by the following StackOverflow post, I came up with this JavaScript version.

function fileSizeToString(size) {
    var suffix = ["B", "KB", "MB", "GB"];

    var place = Math.floor(Math.log(size) / Math.log(1024));
    var fileSize = Math.round(size / Math.pow(1024, place));

    return (fileSize + suffix[place]);
};

As you can see this is a relatively simple function, and really boils down to two lines of code. The first line

var place = Math.floor(Math.log(size) / Math.log(1024));

determines which suffix will be used. While the second line

var fileSize = Math.round(size / Math.pow(1024, place)); 

calculates the file size, which is typically measured in units of 1024.

In my case I only needed to support up to gigabyte file sizes, but the function could easily be modified to support larger sizes.

Happy Coding!

After installing Visual Studio 2010 Service Pack 1, I noticed that intellisense had stopped working in SQL Server Management Studio 2008 R2. The issue was noted in Scott Guthrie’s blog, a few weeks ago. I discovered today that a hotfix is available from Microsoft as a part of SQL Server 2008 R2 cumulative update 7. I’ve installed update 7, and verified that intellisense works again.

Also...



Recent Comments

  • Julianne Dutt: Fine work, I need to hear more from you.Are you read more
  • Vectora Ramirez: Awesome . I will try it in 5 minutes read more
  • Violent Video Games: Epic post :D I'm totally looking forward to seeing more read more
  • Computer Geeks jacksonville: This site just keeps on getting more impressive every time read more
  • sim deals only: thanks for that read more
  • Gourmet Food: thanks, read more
  • Jonathan: "fn-delete" my friend! Welcome to UNIX and overpriced hardware! :) read more
  • Garett: Yes, that's definitely a good one. I'm going to add read more
  • Robin Smith: The book list will put you at a unique place read more
  • Jonathan: Definitely add Programming Collective Intelligence to that list - a read more
Close