Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
file Size Unit Calculator

This is a function to calculate the appropriate unit to describe a file size. If you want a fancier function, try this function: https://gist.github.com/2202887 by @vitronprince

Thanks to maettig for minification tips.

function(
a, //number
c //placeholder
)
{
for(;a>>10;c=-~c)a>>=10; //as long the number is over 1023, divide it by 1024
//a>>10 is the same as a/1024 (Thanks maettig!)
//also set a counter to +1
return a+(" kMGT"[c]||"")+"B"} //return final number + the suffix
function(a,c){for(;a>>10;c=-~c)a>>=10;return a+(" kMGT"[c]||"")+"B"}
Shorter version using proper unicode unit symbols:
function(a,c){for(;a>>10;c=-~c)a>>=10;return a+(" ㎅㎆㎇"[c]||"B")}
{
"name": "fileSizeUnits",
"description": "Function to calculate the appropriate unit to describe a file size",
"keywords": [
"file",
"size",
"units",
"math"
]
}
<!DOCTYPE html>
<title>file Size Unit Calculator</title>
<div>Expected value: <b>269MB</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var fileSizeUnits = function(a,c){for(;a>>10;c=-~c)a>>=10;return a+(" kMGT"[c]||"")+"B"}
document.getElementById( "ret" ).innerHTML = fileSizeUnits(282630144)​
</script>

maettig commented Apr 3, 2012

What about this? Saves 3 bytes. I'm not sure if it works in all cases.

function(a,c){for(;a>>10;c=-~c)a>>=10;return~~a+" kMGT"[c|0]+"B"}
Owner

williammalo commented Apr 3, 2012

@maettig
GENIUS!
right shift operator ftw!
not sure about "[c|0]" tho... "|" isn't the same as "||"
example:
20||18 = 20
20|18 = 22

maettig commented Apr 3, 2012

Yea, but it's |0. It's there because c may be "undefined" and must be converted to "0". You can do the same with ~~c.

Edit: I'm wondering about the space. Is it intended to have a space in "15 B" but not in "15MB"?

Owner

williammalo commented Apr 3, 2012

@maettig quote:"I'm wondering about the space. Is it intended to have a space in "15 B" but not in "15MB"?"
Oops! Thats a bug alright, I'll go and fix it. :P
Edit: Fixd!

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