Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 2, 2015 11:49
Show Gist options
  • Save williammalo/2239095 to your computer and use it in GitHub Desktop.
Save williammalo/2239095 to your computer and use it in GitHub Desktop.
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
Copy link

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"?

@williammalo
Copy link
Author

@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