Skip to content

Instantly share code, notes, and snippets.

@EarMaster
Last active April 14, 2020 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EarMaster/6974018 to your computer and use it in GitHub Desktop.
Save EarMaster/6974018 to your computer and use it in GitHub Desktop.
Formats a filesize into a human readable format. First parameter is filesize in bytes, second parameter is the precision of the resulting float and the last parameter is the system (choose between 'decimal' aka SI-based or 'binary' based calculation).
var formatFilesize = function (size, decimals, system) {
size = parseInt(size, 10)
if (!decimals && decimals!==0) decimals = 1
if (!system) system = 'decimal'
var fileSizes = {
decimal: ['Byte', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
binary: ['Byte', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
}
var base = system=='decimal' ? 1000 : 1024
var steps = Math.floor(Math.log(size) / Math.log(base))
return parseFloat((size / Math.pow(base, steps)).toFixed(decimals)) + ' ' + fileSizes[system][steps]
};
@EarMaster
Copy link
Author

@EarMaster
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment