Skip to content

Instantly share code, notes, and snippets.

@vegg89 vegg89/format.ex
Created Aug 20, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.