Hi,
I came up with the following solution to format an integer (bytesize of a file). Is there any better/shorter solution? I esacially don't like the float_as_string()
part.
human_filesize(Size) ->
KiloByte = 1024,
MegaByte = KiloByte * 1024,
GigaByte = MegaByte * 1024,
TeraByte = GigaByte * 1024,
PetaByte = TeraByte * 1024,
human_filesize(Size, [
{PetaByte, "PB"},
{TeraByte, "TB"},
{GigaByte, "GB"},
{MegaByte, "MB"},
{KiloByte, "KB"}
]).
human_filesize(Size, []) ->
integer_to_list(Size) ++ " Byte";
human_filesize(Size, [{Block, Postfix}|List]) ->
case Size >= Block of
true ->
float_as_string(Size / Block) ++ " " ++ Postfix;
false ->
human_filesize(Size, List)
end.
float_as_string(Float) ->
Integer = trunc(Float), % Part before the .
NewFloat = 1 + Float - Integer, % 1.<part behind>
FloatString = float_to_list(NewFloat), % "1.<part behind>"
integer_to_list(Integer) ++ string:sub_string(FloatString, 2, 4).
Edit: Fixed bug round() -> trunc()