{{ message }}

Instantly share code, notes, and snippets.

Last active Oct 2, 2015
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" ] }
 file Size Unit Calculator
Expected value: 269MB
Actual value:

### 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"}`

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

### 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!