Last active
October 7, 2015 08:07
-
-
Save fvdm/3132128 to your computer and use it in GitHub Desktop.
Convert bytes to KiB, MiB, etc.
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
// Convert bytes to KiB, MiB, etc. (object) | |
// humanBytes( number, numDecimals ) | |
// ex. humanBytes( 10714 ) = { number: 10, str: "10 KiB", unit: "KiB" } | |
// ex. humanBytes( 10714 ).str = "10 KiB" | |
// ex. humanBytes( 10714, 2 ).str = "10.46 KiB" | |
function humanBytes( bytes, decimals ) { | |
var units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; | |
var unit = 'B'; | |
var num = bytes; | |
var dec = decimals !== undefined ? Math.pow( 10, decimals ) : 1; | |
var i = 0; | |
while( num >= 1024 ) { | |
if( units[i] == undefined ) { | |
break; | |
} | |
num = num / 1024; | |
unit = units[i]; | |
i++; | |
} | |
num = Math.round( num * dec ) / dec; | |
return { | |
str: num +' '+ unit, | |
unit: unit, | |
number: num | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment