Skip to content

Instantly share code, notes, and snippets.

@sarahhodne
Created December 19, 2009 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarahhodne/260184 to your computer and use it in GitHub Desktop.
Save sarahhodne/260184 to your computer and use it in GitHub Desktop.
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