Skip to content

Instantly share code, notes, and snippets.

@darelf
Last active November 19, 2015 19:02
Show Gist options
  • Save darelf/03cc54be3626960f481d to your computer and use it in GitHub Desktop.
Save darelf/03cc54be3626960f481d to your computer and use it in GitHub Desktop.
Format File Sizes
-module(display).
-export([format/1,format/2]).
format(Num) -> format(Num, 2).
format(Num, Precision) ->
Abs = abs(Num),
TB = math:pow(10,12),
GB = math:pow(10,9),
MB = math:pow(10,6),
KB = math:pow(10,3),
{Suffix, Value} =
if
Abs >= TB ->
{"TB", Abs/TB};
Abs < TB, Abs >= GB ->
{"GB", Abs/GB};
Abs < GB, Abs >= MB ->
{"MB", Abs/MB};
Abs < MB, Abs >= KB ->
{"KB", Abs/KB};
true ->
{"B", Abs}
end,
io_lib:format("~." ++ integer_to_list(Precision) ++ "f~s",[Value, Suffix]).
%% for logging, I end up doing lists:flatten on this output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment