Skip to content

Instantly share code, notes, and snippets.

@vegg89
Created August 20, 2019 15:17
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 vegg89/fee7454de65b37a68465c21c14c92da5 to your computer and use it in GitHub Desktop.
Save vegg89/fee7454de65b37a68465c21c14c92da5 to your computer and use it in GitHub Desktop.
Format bytes to B, KB, MB, GB
defmodule PhoenixObserver.Format do
def number_to_human_size(size) when is_integer(size) and size < 1024, do: "#{size} B"
def number_to_human_size(size) when size < 1024 * 1024, do: "#{Float.round(size / 1024, 4)} KB"
def number_to_human_size(size) when size < 1024 * 1024 * 1024,
do: "#{Float.round(size / (1024 * 1024), 4)} MB"
def number_to_human_size(size) when size < 1024 * 1024 * 1024 * 1024 do
"#{Float.round(size / (1024 * 1024 * 1024), 4)} GB"
end
def number_to_human_size(size), do: "#{size} ??"
def to_percentage(num) when num < 0.1, do: "#{Float.round(num * 100, 2)}%"
def to_percentage(num) when num < 1, do: "#{Float.round(num * 100, 2)}%"
def to_percentage(_), do: "100%"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment