Created
December 19, 2009 18:24
-
-
Save sarahhodne/260184 to your computer and use it in GitHub Desktop.
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
def number_to_human_size(number) | |
return nil if number.nil? | |
storage_units_format = '%n %u' | |
if number.to_i < 1024 | |
unit = number > 1 ? 'Bytes' : 'Byte' | |
return storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit) | |
else | |
max_exp = STORAGE_UNITS.size - 1 | |
number = Float(number) | |
exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024 | |
exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit | |
number /= 1024 ** exponent | |
unit = %w(Byte KB MB GB TB)[exponent] | |
return storage_units_format.gsub(/%n/, number).gsub(/%u/, unit) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment