Skip to content

Instantly share code, notes, and snippets.

@larsch
Created September 22, 2014 04:02
Show Gist options
  • Select an option

  • Save larsch/932b27ed2d26019e1105 to your computer and use it in GitHub Desktop.

Select an option

Save larsch/932b27ed2d26019e1105 to your computer and use it in GitHub Desktop.
Number to human file size conversion (IEC units)
def human_size(n)
return "0 B" if n.zero?
sizes = %w{B KiB MiB GiB TiB PiB EiB ZiB YiB}
x = (Math.log(n) / Math.log(1024)).floor
n = n / (1024.0 ** x)
n = n.round(2)
n = n.to_i if n.round == n
"#{n} #{sizes[x]}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment