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

发布于 2024-08-19 14:42:45 字数 1000 浏览 2 评论 0原文

我想出了以下解决方案来格式化整数(文件的字节大小)。有更好/更短的解决方案吗?我特别不喜欢 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).

编辑:修复了错误 round() ->截断()

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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我家小可爱 2024-08-26 14:42:45
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]).

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

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]).

Note that this returns an iolist. If you need a string, you can convert that to binary and that to string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文