Last active
April 14, 2020 12:02
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
C#: https://gist.github.com/EarMaster/cde681fa6b7d6b307e8e7ed0d3847662