以人类可读的方式格式化字节大小的简单方法?

Zei*_*ssS 2 floating-point erlang formatting

我想出了以下解决方案来格式化整数(文件的字节大小).有没有更好/更短的解决方案?我特意不喜欢这float_as_string()部分.

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).
Run Code Online (Sandbox Code Playgroud)

编辑:修复bug round() - > trunc()

Zed*_*Zed 5

human_filesize(Size) -> human_filesize(Size, ["B","KB","MB","GB","TB","PB"]).

human_filesize(S, [_|[_|_] = L]) when S >= 1024 -> human_filesize(S/1024, L);
human_filesize(S, [M|_]) ->
    io_lib:format("~.2f ~s", [float(S), M]).
Run Code Online (Sandbox Code Playgroud)

请注意,这将返回一个iolist.如果需要字符串,可以将其转换为二进制,将其转换为字符串.