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!